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): launch the app after import and trust Chrome on its Safe Storage key (#4445)

ddupont1522b052d51a
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/teleport.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/teleport.rs
index ad0433c2fc..951bd918a0 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/services/teleport.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/services/teleport.rs
@@ -523,6 +523,12 @@ impl TeleportService for TeleportServiceImpl {
"close_running_app: not supported by this driver; close the app first".into(),
);
}
+ for notice in &outcome.notices {
+ skipped.push(format!("notice: {notice}"));
+ }
+ if let Some(why) = &outcome.launch_error {
+ skipped.push(format!("launch: {why}"));
+ }
Ok(Response::new(ImportSessionResponse {
received_bytes: import.received,
duplicate,
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/tests/common/mod.rs b/libs/cua-spacesd/crates/cua-spacesd-server/tests/common/mod.rs
index 783ce1810b..c1438c9f05 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/tests/common/mod.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/tests/common/mod.rs
@@ -273,7 +273,15 @@ pub async fn target() -> Target {
..ServerConfig::default()
};
let ctx = ServerContext::new(config, Some(IN_PROCESS_TOKEN.into()));
- let host = Arc::new(cua_spacesd_teleport::FakeHost::new());
+ // Everything fails by default (nothing running, no Keychain), except
+ // launching: on macOS the app is opened through `open`, which succeeds.
+ let host = Arc::new(cua_spacesd_teleport::FakeHost::new().with_responder(|c| {
+ Ok(if c.kind == cua_spacesd_teleport::EffectKind::AppLaunch {
+ cua_spacesd_teleport::host::HostOutput::ok("")
+ } else {
+ cua_spacesd_teleport::host::HostOutput::failed()
+ })
+ }));
let receiver = Arc::new(cua_spacesd_teleport::Receiver::with_host(
home.path().to_path_buf(),
host.clone(),
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 3f0cbfc0eb..c255d01ff1 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
@@ -34,7 +34,7 @@ use cua_teleport_bundle::keychain::KeychainItem;
use cua_teleport_bundle::Platform;
use crate::host::HostEffects;
-use crate::keychain::{install_generic, read_secret};
+use crate::keychain::{install_generic_noted, read_secret, trusted_app_for};
use crate::ledger::ImportRecord;
use crate::{Result, TeleportError};
@@ -85,14 +85,18 @@ pub fn ensure_safe_storage_secret(
// 0.9 `rand::rng()` free function.
rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut raw);
let secret = hex::encode(raw).into_bytes();
- install_generic(
+ // Created with the browser trusted from the start: its team id goes in the
+ // item's partition list, so the browser reads its own key without the
+ // "wants to access key ... enter the login keychain password" dialog.
+ install_generic_noted(
host,
&KeychainItem {
service: service.to_string(),
account: account.to_string(),
secret: secret.clone(),
- trust_app: None,
+ trust_app: trusted_app_for(service).map(str::to_string),
},
+ &mut record.notices,
)?;
record.keychain_installed(service, account);
Ok(secret)
@@ -197,17 +201,33 @@ pub fn install_cookies(
"re-encrypting cookies for a Windows destination (DPAPI) is not supported yet".into(),
));
}
- 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));
+ // Which file Chrome reads depends on its version (see
+ // [`cookies_db_paths`]), and the destination's Chrome may not have run
+ // yet, so write every location it could use. The unused copy is inert.
+ let mut written = 0;
+ for db in cookies_db_paths(profile_dir) {
+ written = written.max(install_into_db(&db, &key, items, record)?);
+ }
+ Ok(written)
+}
+/// Writes `items`, encrypted under `key`, into the cookie database at `db`
+/// (created first when absent). Returns how many rows were written.
+fn install_into_db(
+ db: &Path,
+ key: &[u8; 16],
+ items: &[CookieItem],
+ record: &mut ImportRecord,
+) -> Result<usize> {
if !db.is_file() {
// Never-launched browser: create the database Chrome itself would.
- create_cookies_db(&db)
+ create_cookies_db(db)
.map_err(|e| TeleportError::Provider(format!("creating Cookies failed: {e}")))?;
}
- let conn = rusqlite::Connection::open(&db)
+ let conn = rusqlite::Connection::open(db)
.map_err(|e| TeleportError::Provider(format!("opening Cookies failed: {e}")))?;
let present = existing_columns(&conn, "cookies")
.map_err(|e| TeleportError::Provider(format!("reading Cookies schema failed: {e}")))?;
@@ -244,7 +264,7 @@ pub fn install_cookies(
let mut written = 0usize;
for item in items {
let plain = plaintext_for(digest_values, &item.host_key, &item.value);
- let encrypted = chromium_crypto::encrypt_v10(&key, &plain);
+ let encrypted = chromium_crypto::encrypt_v10(key, &plain);
let mut args: Vec<rusqlite::types::Value> = Vec::with_capacity(columns.len());
for column in &columns {
args.push(match *column {
@@ -275,7 +295,7 @@ pub fn install_cookies(
// had. Instead, the exact row -- by Chromium's own uniqueness for
// one (`host_key`, `name`, `path`) -- so wipe can `DELETE` only
// this row later.
- record.cookie_row_written(&db, &item.host_key, &item.name, &item.path);
+ record.cookie_row_written(db, &item.host_key, &item.name, &item.path);
written += 1;
}
Ok(written)
@@ -290,17 +310,25 @@ const CREATED_META_VERSION: i64 = HOST_KEY_DIGEST_META_VERSION;
/// `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 {
+/// Every place `profile_dir`'s cookie database may live. Chrome moved it to
+/// `Network/Cookies` in 96 and, in current builds (154 verified in a macOS
+/// Space), reads `Cookies` in the profile root again; Chromium forks differ
+/// too. Existing databases are all written into; with none (a destination
+/// Chrome that never ran, so its version is unknown) both are created, since
+/// the one Chrome does not read is harmless and the one it does is not left
+/// missing -- a missing one is a silently signed-out profile.
+fn cookies_db_paths(profile_dir: &Path) -> Vec<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
+ let existing: Vec<_> = [&network, &legacy]
+ .into_iter()
+ .filter(|p| p.is_file())
+ .cloned()
+ .collect();
+ if existing.is_empty() {
+ vec![network, legacy]
} else {
- network
+ existing
}
}
@@ -609,8 +637,9 @@ mod tests {
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);
+ // The root `Cookies` is the one Chrome 154 reads: both are written.
+ assert!(profile.join("Cookies").is_file());
+ assert_eq!(record.cookie_rows.len(), 2);
assert_eq!(record.cookie_rows[0].db, db);
let conn = rusqlite::Connection::open(&db).unwrap();
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
index f7c3e45cb4..05c1ae6d43 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
@@ -145,146 +145,204 @@ fn add_command_line(item: &KeychainItem, keychain: &str) -> std::io::Result<Stri
/// authorization. Non-macOS is a no-op reporting success (there is nothing to
/// install). Returns `Ok` on success.
pub fn install_generic(host: &dyn HostEffects, item: &KeychainItem) -> std::io::Result<()> {
+ install_generic_noted(host, item, &mut Vec::new())
+}
+
+/// [`install_generic`], also telling the caller (in `notes`, user-presentable)
+/// when the item was installed but could not be pre-authorized for its app,
+/// so the app will ask once for the Space's login password.
+///
+/// The partition-list write that pre-authorizes the app needs the password of
+/// the keychain the item is in. The target keychain is tried first; when none
+/// of the passwords this guest can know opens it (the login keychain of an
+/// image whose autologin password file is wrong has a password nobody knows),
+/// the item moves to a keychain spacesd owns (`cua.keychain-db`, a password
+/// it knows), which becomes the default and first on the search list, where
+/// the write succeeds and the app reads the key silently.
+pub fn install_generic_noted(
+ host: &dyn HostEffects,
+ item: &KeychainItem,
+ notes: &mut Vec<String>,
+) -> std::io::Result<()> {
#[cfg(target_os = "macos")]
{
- // Install into the DEFAULT keychain (see target_keychain_path): apps
- // read their Safe Storage key / tokens from the DEFAULT keychain, not
- // the search list, so a non-default keychain is not consulted — a
- // teleported Unity Hub whose `unity` token item sat in a search-list-only
- // keychain logged "No tokens found, logging out" and rendered the
- // sign-in screen with every teleported file correct on disk. The
- // destination must therefore keep its login keychain unlocked (the Cua
- // golden resets it at build so autologin unlocks it — see the golden
- // build). `-A` = all apps may read without a per-access prompt; `-U`
- // replaces any existing item.
- // Delete any existing item for this service+account FIRST, rather than
- // replacing it with `-U`. Updating an item the caller does not own needs
- // authorization, and in an unattended destination (a Space) that opens a
- // SecurityAgent dialog nobody can answer: `security add-generic-password
- // -U` then hangs forever, the import never returns, and the teleport
- // looks like a network failure. Creating a *fresh* item never prompts.
- // Deleting is safe here: we are about to write the authoritative value,
- // and a teleport is expected to overwrite the destination's session.
- // Delete from EVERY keychain in the search list, not just the one we
- // are about to write. A stale copy in any other keychain shadows ours:
- // reads resolve through the search list, and an app that minted its own
- // key before the teleport arrived (Unity Hub's Electron "Safe Storage"
- // key, written the moment the Hub launches) will keep winning, leaving
- // the app visibly signed out with the correct account in its database.
- // Deleting is safe: we are about to write the authoritative value, and
- // a teleport is expected to overwrite the destination's session.
- for keychain in search_list_keychains(host) {
- let _ = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security").args([
- "delete-generic-password",
- "-s",
- &item.service,
- "-a",
- &item.account,
- &keychain,
- ]),
- );
- }
-
- // The secret never goes on argv: argv is readable by every local
- // user (`ps`, /proc/<pid>/cmdline). `security -i` reads commands from
- // stdin instead, and the value travels hex-encoded (`-X`, see
- // security(1) add-generic-password), so no quoting of the secret is
- // needed. `-w` as the last argument (prompt) is not usable here: the
- // keychain path must be the final positional argument, and the
- // prompt needs a terminal.
- //
- // `-A`: every application may read this item without an "allow
- // access?" prompt.
- //
- // `-T <app>` looks tighter and was what this did, but it does not
- // actually work here: with only Unity Hub in the ACL (by its correct
- // designated requirement, and with the team id in the item's
- // partition list) a teleported Unity Hub still raised "Unity Hub
- // wants to access key 'unity' in your keychain" on every launch, an
- // unanswerable SecurityAgent dialog inside a Space. The ACL app entry
- // is matched against the *reading* process, and for an Electron app
- // that is not reliably the bundle we can name.
- //
- // The exposure `-A` adds is bounded: the destination of a teleport is a
- // single-user throwaway VM whose whole purpose is to act as the user,
- // and anything that could read the item could equally read the profile
- // it decrypts. Correctness of the unattended run wins.
- //
- // The destination keychain is named explicitly: it is deliberately
- // not the default (see target_keychain_path), so an unqualified add
- // would land the item somewhere the partition-list write below does
- // not touch.
let keychain = target_keychain_path(host).to_string_lossy().into_owned();
- let line = add_command_line(item, &keychain)?;
- let output = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security")
- .args(["-q", "-i"])
- .stdin(line.into_bytes()),
- )?;
- // Interactive mode's exit status does not reliably reflect the
- // command's, so confirm the item exists (attributes only: neither
- // `-g` nor `-w`, so no secret is printed).
- let present = output.success
- && host
- .run(
- &HostCommand::new(EffectKind::KeychainRead, "security").args([
- "find-generic-password",
- "-s",
- &item.service,
- "-a",
- &item.account,
- &keychain,
- ]),
- )
- .map(|o| o.success)
- .unwrap_or(false);
- if !present {
- return Err(std::io::Error::other(format!(
- "security add-generic-password failed for {:?}",
- item.service
- )));
+ let mut authorized = install_into(host, item, &keychain)?;
+ if !authorized && std::env::var_os("CUA_ENV_KEYCHAIN").is_none() {
+ if let Some(known) = adopt_known_keychain(host) {
+ if known != keychain {
+ eprintln!(
+ "teleport: {keychain} does not take a password this Space knows; \
+ moving {:?} to {known}",
+ item.service
+ );
+ authorized = install_into(host, item, &known)?;
+ }
+ }
+ }
+ if !authorized {
+ let app = item
+ .service
+ .strip_suffix(" Safe Storage")
+ .unwrap_or(&item.service);
+ notes.push(format!(
+ "{app} will ask once for the Space's login password (its saved key could not \
+ be pre-authorized); enter it and choose Always Allow"
+ ));
}
- // `-T <app>` puts the app in the item's ACL, but macOS *also* gates
- // reads on the item's partition list. Without the app's code-signing
- // team in it, the trusted app still gets "<App> wants to access key
- // '<service>' in your keychain. To allow this, enter the 'login'
- // keychain password." — an unanswerable dialog inside an unattended
- // Space, which is what left a teleported Unity Hub signed in but
- // unlicensed ("Access token is unavailable").
- // ALWAYS, not only when a trust app is known: macOS gates reads on the
- // partition list independently of the ACL, and an item created by
- // `security` gets `apple-tool:` — which excludes every app that is not
- // an Apple command-line tool.
- set_partition_list(
- host,
- &item.service,
- &item.account,
- item.trust_app
- .as_deref()
- .and_then(|app| team_identifier(host, app))
- .as_deref(),
- );
- // Re-open the keychain IMMEDIATELY, per item, not just once after the
- // whole bundle. `set_partition_list` takes `-k <password>`, and every
- // `security` subcommand that does unlocks the keychain for the call and
- // RE-LOCKS it on the way out. In a Cua Space that keychain is also the
- // DEFAULT one, so for as long as it stays locked any process that
- // reaches for the default keychain — Spotlight's mdworker is the one
- // that actually did it — raises "<Process> wants to use the '<keychain>'
- // keychain", a SecurityAgent dialog nothing in an unattended Space can
- // answer. Doing this only after the last item leaves that window open
- // across every item but the last.
ensure_login_unlocked(host);
Ok(())
}
#[cfg(not(target_os = "macos"))]
{
- let _ = (host, item);
+ let _ = (host, item, notes);
Ok(())
}
}
+/// Adds `item` to `keychain` and authorizes its app. `Ok(true)` when the app
+/// is pre-authorized (the partition list took); `Ok(false)` when the item is
+/// installed but the app may still prompt.
+#[cfg(target_os = "macos")]
+fn install_into(
+ host: &dyn HostEffects,
+ item: &KeychainItem,
+ keychain: &str,
+) -> std::io::Result<bool> {
+ // Install into the DEFAULT keychain (see target_keychain_path): apps
+ // read their Safe Storage key / tokens from the DEFAULT keychain, not
+ // the search list, so a non-default keychain is not consulted — a
+ // teleported Unity Hub whose `unity` token item sat in a search-list-only
+ // keychain logged "No tokens found, logging out" and rendered the
+ // sign-in screen with every teleported file correct on disk. The
+ // destination must therefore keep its login keychain unlocked (the Cua
+ // golden resets it at build so autologin unlocks it — see the golden
+ // build). `-A` = all apps may read without a per-access prompt; `-U`
+ // replaces any existing item.
+ // Delete any existing item for this service+account FIRST, rather than
+ // replacing it with `-U`. Updating an item the caller does not own needs
+ // authorization, and in an unattended destination (a Space) that opens a
+ // SecurityAgent dialog nobody can answer: `security add-generic-password
+ // -U` then hangs forever, the import never returns, and the teleport
+ // looks like a network failure. Creating a *fresh* item never prompts.
+ // Deleting is safe here: we are about to write the authoritative value,
+ // and a teleport is expected to overwrite the destination's session.
+ // Delete from EVERY keychain in the search list, not just the one we
+ // are about to write. A stale copy in any other keychain shadows ours:
+ // reads resolve through the search list, and an app that minted its own
+ // key before the teleport arrived (Unity Hub's Electron "Safe Storage"
+ // key, written the moment the Hub launches) will keep winning, leaving
+ // the app visibly signed out with the correct account in its database.
+ // Deleting is safe: we are about to write the authoritative value, and
+ // a teleport is expected to overwrite the destination's session.
+ for keychain in search_list_keychains(host) {
+ let _ = host.run(
+ &HostCommand::new(EffectKind::KeychainWrite, "security").args([
+ "delete-generic-password",
+ "-s",
+ &item.service,
+ "-a",
+ &item.account,
+ &keychain,
+ ]),
+ );
+ }
+
+ // The secret never goes on argv: argv is readable by every local
+ // user (`ps`, /proc/<pid>/cmdline). `security -i` reads commands from
+ // stdin instead, and the value travels hex-encoded (`-X`, see
+ // security(1) add-generic-password), so no quoting of the secret is
+ // needed. `-w` as the last argument (prompt) is not usable here: the
+ // keychain path must be the final positional argument, and the
+ // prompt needs a terminal.
+ //
+ // `-A`: every application may read this item without an "allow
+ // access?" prompt.
+ //
+ // `-T <app>` looks tighter and was what this did, but it does not
+ // actually work here: with only Unity Hub in the ACL (by its correct
+ // designated requirement, and with the team id in the item's
+ // partition list) a teleported Unity Hub still raised "Unity Hub
+ // wants to access key 'unity' in your keychain" on every launch, an
+ // unanswerable SecurityAgent dialog inside a Space. The ACL app entry
+ // is matched against the *reading* process, and for an Electron app
+ // that is not reliably the bundle we can name.
+ //
+ // The exposure `-A` adds is bounded: the destination of a teleport is a
+ // single-user throwaway VM whose whole purpose is to act as the user,
+ // and anything that could read the item could equally read the profile
+ // it decrypts. Correctness of the unattended run wins.
+ //
+ // The destination keychain is named explicitly: it is deliberately
+ // not the default (see target_keychain_path), so an unqualified add
+ // would land the item somewhere the partition-list write below does
+ // not touch.
+ let line = add_command_line(item, keychain)?;
+ let output = host.run(
+ &HostCommand::new(EffectKind::KeychainWrite, "security")
+ .args(["-q", "-i"])
+ .stdin(line.into_bytes()),
+ )?;
+ // Interactive mode's exit status does not reliably reflect the
+ // command's, so confirm the item exists (attributes only: neither
+ // `-g` nor `-w`, so no secret is printed).
+ let present = output.success
+ && host
+ .run(
+ &HostCommand::new(EffectKind::KeychainRead, "security").args([
+ "find-generic-password",
+ "-s",
+ &item.service,
+ "-a",
+ &item.account,
+ keychain,
+ ]),
+ )
+ .map(|o| o.success)
+ .unwrap_or(false);
+ if !present {
+ return Err(std::io::Error::other(format!(
+ "security add-generic-password failed for {:?}",
+ item.service
+ )));
+ }
+ // `-T <app>` puts the app in the item's ACL, but macOS *also* gates
+ // reads on the item's partition list. Without the app's code-signing
+ // team in it, the trusted app still gets "<App> wants to access key
+ // '<service>' in your keychain. To allow this, enter the 'login'
+ // keychain password." — an unanswerable dialog inside an unattended
+ // Space, which is what left a teleported Unity Hub signed in but
+ // unlicensed ("Access token is unavailable").
+ // ALWAYS, not only when a trust app is known: macOS gates reads on the
+ // partition list independently of the ACL, and an item created by
+ // `security` gets `apple-tool:` — which excludes every app that is not
+ // an Apple command-line tool.
+ let team = item
+ .trust_app
+ .as_deref()
+ .and_then(|app| team_identifier(host, app))
+ .or_else(|| known_team_id(&item.service).map(str::to_string));
+ let authorized = set_partition_list(
+ host,
+ &item.service,
+ &item.account,
+ team.as_deref(),
+ std::path::Path::new(keychain),
+ );
+ // Re-open the keychain IMMEDIATELY, per item, not just once after the
+ // whole bundle. `set_partition_list` takes `-k <password>`, and every
+ // `security` subcommand that does unlocks the keychain for the call and
+ // RE-LOCKS it on the way out. In a Cua Space that keychain is also the
+ // DEFAULT one, so for as long as it stays locked any process that
+ // reaches for the default keychain — Spotlight's mdworker is the one
+ // that actually did it — raises "<Process> wants to use the '<keychain>'
+ // keychain", a SecurityAgent dialog nothing in an unattended Space can
+ // answer. Doing this only after the last item leaves that window open
+ // across every item but the last.
+ ensure_login_unlocked(host);
+ Ok(authorized)
+}
+
/// Parse a [`KEYCHAIN_ENTRY`] payload and install every item, returning how
/// many were installed. Best-effort: a single item's failure is skipped so the
/// rest still land (a partly-usable session beats none).
@@ -305,7 +363,7 @@ pub fn install_all_recorded(
let installed = items
.iter()
.filter(|item| {
- let ok = install_generic(host, item).is_ok();
+ let ok = install_generic_noted(host, item, &mut record.notices).is_ok();
if ok && cfg!(target_os = "macos") {
record.keychain_installed(&item.service, &item.account);
}
@@ -355,33 +413,23 @@ fn team_identifier(host: &dyn HostEffects, app_path: &str) -> Option<String> {
/// the destination app itself. Best-effort — a failure here only means the app
/// may prompt, so it must not fail the install.
#[cfg(target_os = "macos")]
-fn set_partition_list(host: &dyn HostEffects, service: &str, account: &str, team_id: Option<&str>) {
- // Target whatever keychain the item actually went into, which is the
- // DEFAULT keychain: `security add-generic-password` without `-k` writes
- // there, not necessarily to login.keychain-db. Hardcoding the login
- // keychain silently no-ops on a destination whose default is something
- // else, and the app then hits "<App> wants to access key '<service>' in
- // your keychain" — which is exactly what a Cua Space does, because the
- // login keychain macOS creates at login does not take a password we know,
- // so the Space installs a `cua` keychain and makes that the default
- // instead. Falling back to the login keychain keeps the old behaviour for
- // hosts that never changed their default.
- //
- // "does not take a password we know" re-verified 2026-09-12 inside a Space,
- // in the aqua session as uid 501: this exact call with `-k lume` against
- // login.keychain-db returns "SecKeychainItemSetAccessWithPassword: The user
- // name or passphrase you entered is not correct". `security unlock-keychain
- // -p lume login.keychain-db` succeeding does NOT contradict that — unlocking
- // an already-unlocked keychain never checks the password.
- //
- // The destination keychain must therefore also be the DEFAULT one, not just
- // first on the search list: Unity Hub's keyring binding (and anything else
- // built on a `SecKeychain::default()`-style lookup) resolves the default
- // keychain only, so an item parked in a non-default keychain reads as
- // absent. The Space's prepare-space.sh makes the `cua` keychain the default
- // for that reason; CUA_ENV_KEYCHAIN names the same one.
- let path = target_keychain_path(host);
- let pw = std::env::var("CUA_ENV_LOGIN_KEYCHAIN_PW").unwrap_or_else(|_| "lume".to_string());
+fn set_partition_list(
+ host: &dyn HostEffects,
+ service: &str,
+ account: &str,
+ team_id: Option<&str>,
+ path: &std::path::Path,
+) -> bool {
+ // Targets the keychain the item actually went into (`path`). Re-verified
+ // 2026-09-12 inside a Space, in the aqua session as uid 501: this exact
+ // call with `-k lume` against the login keychain of an image with the
+ // autologin-password bug returns "SecKeychainItemSetAccessWithPassword:
+ // The user name or passphrase you entered is not correct" --
+ // `security unlock-keychain -p lume` succeeding does NOT contradict that,
+ // unlocking an already-unlocked keychain never checks the password.
+ // Every password this guest can know is therefore tried in turn
+ // ([`keychain_passwords`]); the caller moves to a keychain with a known
+ // password when none opens this one.
let partitions = match team_id {
// apple-tool: keeps /usr/bin/security itself able to touch the item
// (the golden's per-boot verification uses it), apple: covers
@@ -389,36 +437,160 @@ fn set_partition_list(host: &dyn HostEffects, service: &str, account: &str, team
Some(id) => format!("teamid:{id},apple:,apple-tool:"),
None => "apple:,apple-tool:".to_string(),
};
- let mut args: Vec<String> = vec![
- "set-generic-password-partition-list".into(),
- "-S".into(),
- partitions,
- "-k".into(),
+ let mut last_error = String::new();
+ for pw in keychain_passwords(host) {
+ let mut args: Vec<String> = vec![
+ "set-generic-password-partition-list".into(),
+ "-S".into(),
+ partitions.clone(),
+ "-k".into(),
+ pw,
+ "-s".into(),
+ service.to_string(),
+ ];
+ if !account.is_empty() {
+ args.push("-a".into());
+ args.push(account.to_string());
+ }
+ args.push(path.to_string_lossy().into_owned());
+ match host.run(&HostCommand::new(EffectKind::KeychainWrite, "security").args(args)) {
+ Ok(out) if out.success => return true,
+ Ok(out) => last_error = String::from_utf8_lossy(&out.stderr).trim().to_string(),
+ Err(e) => last_error = e.to_string(),
+ }
+ }
+ // Reported, not swallowed: the failure mode is a SecurityAgent dialog
+ // nothing in an unattended destination can answer.
+ eprintln!(
+ "warning: could not authorize keychain item {service:?} for silent reads \
+ ({last_error}); the destination app will raise a \"wants to access key\" dialog. \
+ Keychain: {}",
+ path.display()
+ );
+ false
+}
+
+/// Passwords this guest might have for a keychain, most specific first:
+/// `CUA_ENV_LOGIN_KEYCHAIN_PW`; the first line of `~/.cua/spacesd/keychain-password`
+/// or `/etc/cua/keychain-password` (a provisioner writes one, 0600/0644 root
+/// or the desktop user); then the Lume image's account password `lume`.
+#[cfg(target_os = "macos")]
+fn keychain_passwords(host: &dyn HostEffects) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ let mut push = |p: String| {
+ let p = p.trim_end_matches(['\r', '\n']).to_string();
+ if !p.is_empty() && !out.contains(&p) {
+ out.push(p);
+ }
+ };
+ if let Ok(p) = std::env::var("CUA_ENV_LOGIN_KEYCHAIN_PW") {
+ push(p);
+ }
+ let mut files = vec![std::path::PathBuf::from("/etc/cua/keychain-password")];
+ if let Some(home) = host.home_dir() {
+ files.insert(0, home.join(".cua/spacesd/keychain-password"));
+ }
+ for f in files {
+ if let Ok(text) = std::fs::read_to_string(f) {
+ if let Some(line) = text.lines().next() {
+ push(line.to_string());
+ }
+ }
+ }
+ push("lume".to_string());
+ out
+}
+
+/// The code-signing Team Identifier of the Chromium-family browsers whose
+/// Safe Storage key this crate installs, used when the app is not installed
+/// yet to be inspected with `codesign`: the partition list must name the
+/// browser's team or the browser prompts for the key.
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+fn known_team_id(service: &str) -> Option<&'static str> {
+ match service {
+ "Chrome Safe Storage" => Some("EQHXZ8M8AV"),
+ "Microsoft Edge Safe Storage" => Some("UBF8T346G9"),
+ "Brave Safe Storage" => Some("KL8N8XSYF4"),
+ _ => None,
+ }
+}
+
+/// The macOS app bundle that owns Safe Storage item `service`, for
+/// [`KeychainItem::trust_app`].
+pub(crate) fn trusted_app_for(service: &str) -> Option<&'static str> {
+ match service {
+ "Chrome Safe Storage" => Some("/Applications/Google Chrome.app"),
+ "Chromium Safe Storage" => Some("/Applications/Chromium.app"),
+ "Microsoft Edge Safe Storage" => Some("/Applications/Microsoft Edge.app"),
+ "Brave Safe Storage" => Some("/Applications/Brave Browser.app"),
+ _ => None,
+ }
+}
+
+/// Makes sure a keychain whose password this guest knows exists, is unlocked,
+/// first on the search list and the default, and returns its path. `None`
+/// when it cannot be created.
+#[cfg(target_os = "macos")]
+fn adopt_known_keychain(host: &dyn HostEffects) -> Option<String> {
+ let home = host.home_dir()?;
+ let path = home.join("Library/Keychains/cua.keychain-db");
+ let path_str = path.to_string_lossy().into_owned();
+ let pw = keychain_passwords(host).into_iter().next()?;
+ let sec = |args: Vec<String>| {
+ host.run(&HostCommand::new(EffectKind::KeychainWrite, "security").args(args))
+ .map(|o| o.success)
+ .unwrap_or(false)
+ };
+ if !path.exists()
+ && !sec(vec![
+ "create-keychain".into(),
+ "-p".into(),
+ pw.clone(),
+ path_str.clone(),
+ ])
+ {
+ return None;
+ }
+ sec(vec![
+ "unlock-keychain".into(),
+ "-p".into(),
pw,
+ path_str.clone(),
+ ]);
+ sec(vec!["set-keychain-settings".into(), path_str.clone()]);
+ // First on the search list (apps read through it), the rest kept.
+ let mut list = vec![path_str.clone()];
+ if let Ok(o) = host.run(
+ &HostCommand::new(EffectKind::KeychainRead, "security").args([
+ "list-keychains",
+ "-d",
+ "user",
+ ]),
+ ) {
+ for line in String::from_utf8_lossy(&o.stdout).lines() {
+ let p = line.trim().trim_matches('"').to_string();
+ if !p.is_empty() && !list.contains(&p) {
+ list.push(p);
+ }
+ }
+ }
+ let mut args = vec![
+ "list-keychains".to_string(),
+ "-d".into(),
+ "user".into(),
"-s".into(),
- service.to_string(),
];
- if !account.is_empty() {
- args.push("-a".into());
- args.push(account.to_string());
- }
- args.push(path.to_string_lossy().into_owned());
- // Report a failure. This call is best-effort in the sense that the bundle
- // still lands without it, but its failure mode is a SecurityAgent dialog
- // nothing in an unattended destination can answer, so swallowing the error
- // turned a diagnosable misconfiguration into an hour of a demo run staring
- // at a password box. `security` writes the reason to stderr.
- match host.run(&HostCommand::new(EffectKind::KeychainWrite, "security").args(args)) {
- Ok(out) if out.success => {}
- Ok(out) => eprintln!(
- "warning: could not authorize keychain item {service:?} for silent reads \
- ({}); the destination app will raise an \"wants to access key\" dialog. \
- Keychain: {}",
- String::from_utf8_lossy(&out.stderr).trim(),
- path.display()
- ),
- Err(e) => eprintln!("warning: could not run security set-…-partition-list: {e}"),
- }
+ args.extend(list);
+ sec(args);
+ // Default too: some apps resolve only the default keychain.
+ sec(vec![
+ "default-keychain".into(),
+ "-d".into(),
+ "user".into(),
+ "-s".into(),
+ path_str.clone(),
+ ]);
+ Some(path_str)
}
/// The keychain teleported items are installed into.
@@ -685,6 +857,128 @@ mod tests {
assert!(record.keychain_items.is_empty());
}
+ #[cfg(target_os = "macos")]
+ fn chrome_item() -> KeychainItem {
+ KeychainItem {
+ service: "Chrome Safe Storage".into(),
+ account: "Chrome".into(),
+ secret: b"s3cret".to_vec(),
+ trust_app: trusted_app_for("Chrome Safe Storage").map(str::to_string),
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ fn partition_calls(host: &FakeHost) -> Vec<crate::host::HostCommand> {
+ host.calls_of(EffectKind::KeychainWrite)
+ .into_iter()
+ .filter(|c| {
+ c.args.first().map(String::as_str) == Some("set-generic-password-partition-list")
+ })
+ .collect()
+ }
+
+ /// A Safe Storage item we create trusts Chrome from the start: its team id
+ /// is in the partition list even though Chrome is not installed to be
+ /// inspected (so nothing prompts, and no password dialog is needed).
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn chrome_is_trusted_on_the_item_it_is_created_with() {
+ let host = FakeHost::new()
+ .with_home("/nonexistent-fake-home")
+ .with_responder(|c| {
+ Ok(if c.program == "codesign" {
+ HostOutput::failed()
+ } else {
+ HostOutput::ok("")
+ })
+ });
+ let mut notes = Vec::new();
+ install_generic_noted(&host, &chrome_item(), &mut notes).unwrap();
+ assert!(notes.is_empty(), "{notes:?}");
+ let calls = partition_calls(&host);
+ assert_eq!(calls.len(), 1, "{calls:?}");
+ let partitions = &calls[0].args[2];
+ assert!(partitions.contains("teamid:EQHXZ8M8AV"), "{partitions}");
+ assert!(partitions.contains("apple-tool:"), "{partitions}");
+ }
+
+ /// The login keychain's password is not one this guest knows (the image's
+ /// autologin password file is wrong): the item moves to a keychain spacesd
+ /// owns, where the write takes, and Chrome is still authorized silently.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn an_unknown_login_password_moves_the_item_to_a_known_keychain() {
+ let host = FakeHost::new()
+ .with_home("/nonexistent-fake-home")
+ .with_responder(|c| {
+ let last = c.args.last().map(String::as_str).unwrap_or("");
+ Ok(match c.args.first().map(String::as_str) {
+ Some("default-keychain") if c.args.len() == 3 => HostOutput::ok(
+ "\"/nonexistent-fake-home/Library/Keychains/login.keychain-db\"\n",
+ ),
+ Some("set-generic-password-partition-list")
+ if last.ends_with("login.keychain-db") =>
+ {
+ HostOutput {
+ success: false,
+ stdout: vec![],
+ stderr: b"The user name or passphrase you entered is not correct."
+ .to_vec(),
+ }
+ }
+ _ => HostOutput::ok(""),
+ })
+ });
+ let mut notes = Vec::new();
+ install_generic_noted(&host, &chrome_item(), &mut notes).unwrap();
+ assert!(notes.is_empty(), "{notes:?}");
+ let writes = host.calls_of(EffectKind::KeychainWrite);
+ let known = "/nonexistent-fake-home/Library/Keychains/cua.keychain-db";
+ assert!(
+ writes.iter().any(
+ |c| c.args.first().map(String::as_str) == Some("create-keychain")
+ && c.args.last().map(String::as_str) == Some(known)
+ ),
+ "{writes:?}"
+ );
+ assert!(
+ writes.iter().any(
+ |c| c.args.first().map(String::as_str) == Some("default-keychain")
+ && c.args.last().map(String::as_str) == Some(known)
+ ),
+ "{writes:?}"
+ );
+ // Added twice (login, then the known keychain), authorized on the second.
+ assert_eq!(writes.iter().filter(|c| is_add_command(c)).count(), 2);
+ let last = partition_calls(&host).pop().unwrap();
+ assert_eq!(last.args.last().map(String::as_str), Some(known));
+ assert!(last.args[2].contains("teamid:EQHXZ8M8AV"));
+ }
+
+ /// When no password works anywhere, the teleport says so in words the
+ /// user can act on.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn no_working_password_is_reported_to_the_user() {
+ let host = FakeHost::new()
+ .with_home("/nonexistent-fake-home")
+ .with_responder(|c| {
+ Ok(match c.args.first().map(String::as_str) {
+ Some("set-generic-password-partition-list") | Some("create-keychain") => {
+ HostOutput::failed()
+ }
+ _ => HostOutput::ok(""),
+ })
+ });
+ let mut notes = Vec::new();
+ install_generic_noted(&host, &chrome_item(), &mut notes).unwrap();
+ assert_eq!(notes.len(), 1, "{notes:?}");
+ assert!(
+ notes[0].starts_with("Chrome will ask once for the Space's login password"),
+ "{notes:?}"
+ );
+ }
+
#[test]
fn names_with_line_breaks_are_refused() {
let item = KeychainItem {
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
index c14348a56a..47bbfc0e4d 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/ledger.rs
@@ -73,6 +73,10 @@ pub struct ImportRecord {
/// have already called [`Self::file_written`] for it, so this is only
/// the merge case, into a database the import did not create).
pub cookie_rows: Vec<CookieRowRef>,
+ /// Things the user should be told about that did not fail the import
+ /// (e.g. the app will ask once for a password). Reported back to the
+ /// client, never ledgered.
+ pub notices: Vec<String>,
}
impl ImportRecord {
@@ -213,6 +217,7 @@ impl Ledger {
created_dirs: self.directories.clone(),
keychain_items: self.keychain_items.clone(),
cookie_rows: self.cookie_rows.clone(),
+ notices: Vec::new(),
}
}
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/receiver.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/receiver.rs
index 57d01a6941..4c10235766 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/receiver.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/receiver.rs
@@ -46,8 +46,14 @@ pub struct ImportOutcome {
pub imported: Vec<String>,
/// True if the app was launched.
pub launched: bool,
- /// Launched pid, if any.
+ /// Launched pid, if any (`open` does not report one).
pub pid: Option<u32>,
+ /// Why the launch did not happen, when it was asked for and failed. A
+ /// launch failure is not an import failure, but it is never silent: the
+ /// service reports it back to the client.
+ pub launch_error: Option<String>,
+ /// Non-fatal things the user should know (taken from [`ImportRecord`]).
+ pub notices: Vec<String>,
/// Everything the importer wrote (files, created directories, Keychain
/// items), for the import ledger.
pub record: ImportRecord,
@@ -158,23 +164,32 @@ impl Receiver {
.collect();
imported.sort();
imported.dedup();
- let (launched, pid) = if launch {
- let mut command = HostCommand::new(EffectKind::AppLaunch, spec.program.clone())
- .args(spec.args.clone());
- command.env = spec.env.clone();
- command.cwd = spec.cwd.clone().map(PathBuf::from);
- match self.host.spawn(&command) {
- Ok(pid) => (true, Some(pid)),
- Err(_) => (false, None),
+ let (launched, pid, launch_error) = if launch {
+ match launch_app(&*self.host, &spec, Platform::current()) {
+ Ok(pid) => {
+ eprintln!(
+ "teleport: launched {} ({})",
+ provider_id,
+ pid.map(|p| format!("pid {p}"))
+ .unwrap_or_else(|| "via LaunchServices".into())
+ );
+ (true, pid, None)
+ }
+ Err(why) => {
+ eprintln!("warning: teleport: could not launch {provider_id}: {why}");
+ (false, None, Some(why))
+ }
}
} else {
- (false, None)
+ (false, None, None)
};
Ok(ImportOutcome {
provider_id,
imported,
launched,
pid,
+ launch_error,
+ notices: std::mem::take(&mut record.notices),
record,
})
}
@@ -196,6 +211,99 @@ impl Receiver {
}
}
+/// The `.app` bundle a macOS executable path lives in
+/// (`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome` ->
+/// `/Applications/Google Chrome.app`), `None` for a bare program.
+fn app_bundle_of(program: &str) -> Option<&str> {
+ let end = program.find(".app/Contents/MacOS/")? + ".app".len();
+ Some(&program[..end])
+}
+
+/// Opens the imported app. On macOS an app bundle is opened through
+/// LaunchServices (`open -a <bundle> --args ...`), in the logged-in GUI
+/// session: spacesd normally already runs there (its LaunchAgent is
+/// `LimitLoadToSessionType=Aqua`), and when it runs as root the call is moved
+/// into the console user's session with `launchctl asuser`. Spawning the
+/// bundle's inner executable directly (what this did) starts a Dock-less
+/// process that is not registered with LaunchServices. Anything else is
+/// spawned detached. Returns the pid when one is known; `Err` carries a
+/// user-presentable reason.
+pub fn launch_app(
+ host: &dyn HostEffects,
+ spec: &cua_teleport_bundle::LaunchSpec,
+ platform: Platform,
+) -> Result<Option<u32>, String> {
+ let cwd = spec.cwd.clone().map(PathBuf::from);
+ let bundle = match (platform, app_bundle_of(&spec.program)) {
+ (Platform::MacOS, Some(bundle)) => bundle,
+ _ => {
+ let mut command = HostCommand::new(EffectKind::AppLaunch, spec.program.clone())
+ .args(spec.args.clone());
+ command.env = spec.env.clone();
+ command.cwd = cwd;
+ return host
+ .spawn(&command)
+ .map(Some)
+ .map_err(|e| format!("{}: {e}", spec.program));
+ }
+ };
+ let mut open_args: Vec<String> = vec!["-a".into(), bundle.into()];
+ for (k, v) in &spec.env {
+ open_args.push("--env".into());
+ open_args.push(format!("{k}={v}"));
+ }
+ if !spec.args.is_empty() {
+ open_args.push("--args".into());
+ open_args.extend(spec.args.iter().cloned());
+ }
+ let mut program = "/usr/bin/open".to_string();
+ // Running as root (a LaunchDaemon install): enter the console user's GUI
+ // session instead of opening on a session with no windowserver.
+ let is_root = host
+ .run(&HostCommand::new(EffectKind::ProcessLookup, "/usr/bin/id").arg("-u"))
+ .map(|o| o.success && String::from_utf8_lossy(&o.stdout).trim() == "0")
+ .unwrap_or(false);
+ if is_root {
+ let uid = host
+ .run(
+ &HostCommand::new(EffectKind::ProcessLookup, "/usr/bin/stat").args([
+ "-f",
+ "%u",
+ "/dev/console",
+ ]),
+ )
+ .ok()
+ .filter(|o| o.success)
+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
+ .filter(|u| !u.is_empty() && u != "0" && u.bytes().all(|b| b.is_ascii_digit()))
+ .ok_or_else(|| "no user is logged in to the Space's desktop".to_string())?;
+ let mut wrapped = vec![
+ "asuser".to_string(),
+ uid.clone(),
+ "/usr/bin/sudo".into(),
+ "-n".into(),
+ "-u".into(),
+ format!("#{uid}"),
+ "/usr/bin/open".into(),
+ ];
+ wrapped.extend(open_args);
+ open_args = wrapped;
+ program = "/bin/launchctl".into();
+ }
+ let mut command = HostCommand::new(EffectKind::AppLaunch, program)
+ .args(open_args)
+ .timeout(std::time::Duration::from_secs(30));
+ command.cwd = cwd;
+ match host.run(&command) {
+ Ok(out) if out.success => Ok(None),
+ Ok(out) => Err(format!(
+ "open {bundle}: {}",
+ String::from_utf8_lossy(&out.stderr).trim()
+ )),
+ Err(e) => Err(format!("open {bundle}: {e}")),
+ }
+}
+
/// Checks a transfer-relative path: non-empty, `/`-separated, no `..`, not
/// absolute. Returns the normalized path.
pub fn validate_relative_path(relative: &str) -> Result<PathBuf, String> {
@@ -329,6 +437,93 @@ impl IgnoreRules {
mod tests {
use super::*;
+ fn chrome_spec() -> cua_teleport_bundle::LaunchSpec {
+ cua_teleport_bundle::LaunchSpec {
+ program: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into(),
+ args: vec!["--user-data-dir=/h/x".into(), "--no-first-run".into()],
+ env: Vec::new(),
+ cwd: None,
+ restore_windows: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn a_macos_app_opens_through_launch_services() {
+ let host = crate::FakeHost::new().with_responder(|c| {
+ Ok(crate::host::HostOutput {
+ // `id -u` is the desktop user, `open` succeeds.
+ success: true,
+ stdout: if c.program == "/usr/bin/id" {
+ b"501\n".to_vec()
+ } else {
+ vec![]
+ },
+ stderr: vec![],
+ })
+ });
+ let pid = launch_app(&host, &chrome_spec(), Platform::MacOS).unwrap();
+ assert_eq!(pid, None);
+ let calls = host.calls_of(EffectKind::AppLaunch);
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].program, "/usr/bin/open");
+ assert_eq!(
+ calls[0].args,
+ vec![
+ "-a",
+ "/Applications/Google Chrome.app",
+ "--args",
+ "--user-data-dir=/h/x",
+ "--no-first-run"
+ ]
+ );
+ }
+
+ #[test]
+ fn a_root_spacesd_opens_in_the_console_users_session() {
+ let host = crate::FakeHost::new().with_responder(|c| {
+ Ok(crate::host::HostOutput {
+ success: true,
+ stdout: match c.program.as_str() {
+ "/usr/bin/id" => b"0\n".to_vec(),
+ "/usr/bin/stat" => b"501\n".to_vec(),
+ _ => vec![],
+ },
+ stderr: vec![],
+ })
+ });
+ launch_app(&host, &chrome_spec(), Platform::MacOS).unwrap();
+ let call = &host.calls_of(EffectKind::AppLaunch)[0];
+ assert_eq!(call.program, "/bin/launchctl");
+ assert_eq!(&call.args[..2], ["asuser", "501"]);
+ assert!(call.args.contains(&"/usr/bin/open".to_string()));
+ }
+
+ #[test]
+ fn a_failed_open_is_reported_not_swallowed() {
+ let host = crate::FakeHost::new().with_responder(|c| {
+ Ok(crate::host::HostOutput {
+ success: c.program == "/usr/bin/id",
+ stdout: b"501\n".to_vec(),
+ stderr: b"Unable to find application".to_vec(),
+ })
+ });
+ let err = launch_app(&host, &chrome_spec(), Platform::MacOS).unwrap_err();
+ assert!(err.contains("Unable to find application"), "{err}");
+ }
+
+ #[test]
+ fn a_linux_program_is_spawned_directly() {
+ let host = crate::FakeHost::new();
+ let mut spec = chrome_spec();
+ spec.program = "google-chrome".into();
+ let pid = launch_app(&host, &spec, Platform::Linux).unwrap();
+ assert_eq!(pid, Some(crate::FakeHost::FAKE_PID));
+ assert_eq!(
+ host.calls_of(EffectKind::AppLaunch)[0].program,
+ "google-chrome"
+ );
+ }
+
#[test]
fn relative_paths_are_confined() {
assert_eq!(
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
index 6d6cc07285..62c2a13dbf 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
@@ -13,10 +13,12 @@ use std::path::Path;
use std::sync::Arc;
use cua_spacesd_teleport::bundle::BundleWriter;
+use cua_spacesd_teleport::host::HostOutput;
use cua_spacesd_teleport::{EffectKind, FakeHost, ImportError, Receiver, TransferScope};
fn fake_receiver(dest: &Path) -> (Arc<FakeHost>, Receiver) {
- let host = Arc::new(FakeHost::new());
+ // Every host command "succeeds" (`open` returns 0), nothing real runs.
+ let host = Arc::new(FakeHost::new().with_responder(|_| Ok(HostOutput::ok("501"))));
let receiver = Receiver::with_host(dest.to_path_buf(), host.clone());
(host, receiver)
}
@@ -53,8 +55,18 @@ fn import_lands_files_and_launches_through_the_fake_host() {
.import_bytes(&chrome_bundle(), "chrome", true)
.unwrap();
assert_eq!(outcome.provider_id, "chrome");
- assert!(outcome.launched);
- assert_eq!(outcome.pid, Some(0));
+ assert!(outcome.launched, "{:?}", outcome.launch_error);
+ assert!(outcome.launch_error.is_none());
+ // macOS opens the app through LaunchServices (no pid); elsewhere the
+ // program is spawned.
+ assert_eq!(
+ outcome.pid,
+ if cfg!(target_os = "macos") {
+ None
+ } else {
+ Some(0)
+ }
+ );
// The import remaps the Chrome profile to the DESTINATION platform's
// user-data directory.
let user_data_dir = if cfg!(target_os = "macos") {
@@ -71,12 +83,45 @@ fn import_lands_files_and_launches_through_the_fake_host() {
);
let launches = host.calls_of(EffectKind::AppLaunch);
assert_eq!(launches.len(), 1, "{:?}", host.calls());
+ if cfg!(target_os = "macos") {
+ assert_eq!(launches[0].program, "/usr/bin/open");
+ assert_eq!(
+ launches[0].args[..2],
+ ["-a", "/Applications/Google Chrome.app"]
+ );
+ }
assert!(launches[0]
.args
.iter()
.any(|a| a.starts_with("--user-data-dir=")));
}
+/// A launch that fails is reported with its reason, not silently dropped, and
+/// does not fail the import.
+#[cfg(target_os = "macos")]
+#[test]
+fn a_failed_launch_is_reported_and_the_import_still_succeeds() {
+ let dest = tempfile::tempdir().unwrap();
+ let host = Arc::new(FakeHost::new().with_responder(|c| {
+ Ok(if c.kind == EffectKind::AppLaunch {
+ HostOutput {
+ success: false,
+ stdout: vec![],
+ stderr: b"The application cannot be opened".to_vec(),
+ }
+ } else {
+ HostOutput::ok("501")
+ })
+ }));
+ let receiver = Receiver::with_host(dest.path().to_path_buf(), host);
+ let outcome = receiver
+ .import_bytes(&chrome_bundle(), "chrome", true)
+ .unwrap();
+ assert!(!outcome.launched);
+ let why = outcome.launch_error.expect("reason");
+ assert!(why.contains("cannot be opened"), "{why}");
+}
+
#[test]
fn import_without_launch_records_nothing() {
let dest = tempfile::tempdir().unwrap();
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 1dc905f509..a700e6f75f 100644
--- a/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
+++ b/libs/cua-spacesd/tests/teleport-e2e/tests/send_import.rs
@@ -45,11 +45,12 @@ async fn guest() -> Guest {
let ctx = ServerContext::new(config, Some(TOKEN.into()));
// 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.
+ // call and the app launch (`open` on macOS) succeed. 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 {
+ let launches = c.kind == cua_spacesd_teleport::EffectKind::AppLaunch;
+ if (c.program != "security" && !launches) || reads_secret {
Ok(cua_spacesd_teleport::HostOutput::failed())
} else {
Ok(cua_spacesd_teleport::HostOutput::ok(""))
@@ -267,6 +268,13 @@ async fn cookies_land_in_a_chrome_that_was_never_launched() {
.join(user_data)
.join("Default/Network/Cookies");
assert!(db.is_file(), "no cookies database was created");
+ // Current Chrome (154) reads `Default/Cookies`, older builds
+ // `Default/Network/Cookies`: both carry the session, so neither a new nor
+ // an old guest Chrome comes up signed out.
+ assert!(
+ db.with_file_name("..").join("Cookies").is_file(),
+ "no root 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| {
diff --git a/libs/cua/crates/cua-keyvault/src/broker.rs b/libs/cua/crates/cua-keyvault/src/broker.rs
index 7b94bb0d92..05f9d4d4f3 100644
--- a/libs/cua/crates/cua-keyvault/src/broker.rs
+++ b/libs/cua/crates/cua-keyvault/src/broker.rs
@@ -361,6 +361,23 @@ pub trait Backend: Send + Sync {
self.deliver(target, provider_id, payloads, expires_ms)
.await
}
+ /// [`Self::deliver_with_progress`], also asking the receiver to launch the
+ /// imported app in the Space's logged-in GUI session (`launch`). The
+ /// default ignores `launch` (a backend that cannot launch reports
+ /// `launched: false` in its [`DeliveryOutcome`]).
+ async fn deliver_launching(
+ &self,
+ target: &str,
+ provider_id: &str,
+ payloads: Vec<ItemPayload>,
+ expires_ms: u64,
+ stage: StageSink,
+ launch: bool,
+ ) -> Result<DeliveryOutcome> {
+ let _ = launch;
+ self.deliver_with_progress(target, provider_id, payloads, expires_ms, stage)
+ .await
+ }
/// Wipes an earlier import from `target`.
async fn wipe(&self, target: &str, import_id: &str) -> Result<Vec<String>>;
/// Tells the UI a consent request is waiting (open the Keyvault page).
@@ -1577,6 +1594,22 @@ impl Broker {
target: String,
save: bool,
stage: Option<StageSink>,
+ ) -> Result<TeleportOutcome> {
+ self.import_and_teleport_launching(caller, spec, target, save, true, stage)
+ .await
+ }
+
+ /// [`Self::import_and_teleport_with_progress`] with an explicit `launch`:
+ /// whether the Space opens the app after importing it (the default for a
+ /// teleport; `cua teleport push --no-launch` turns it off).
+ pub async fn import_and_teleport_launching(
+ &self,
+ caller: &CallerIdentity,
+ spec: ImportSpec,
+ target: String,
+ save: bool,
+ launch: bool,
+ stage: Option<StageSink>,
) -> Result<TeleportOutcome> {
let tell = |s: TeleportStage| {
if let Some(f) = &stage {
@@ -1622,7 +1655,13 @@ impl Broker {
target: target.clone(),
};
let result = self
- .teleport_inner(caller, req, PresenceAlready::Confirmed, stage.clone())
+ .teleport_inner(
+ caller,
+ req,
+ PresenceAlready::Confirmed,
+ stage.clone(),
+ launch,
+ )
.await;
crate::telemetry::teleport(&self.telemetry, caller, &app, started, &result, n);
if !save {
@@ -2458,7 +2497,7 @@ impl Broker {
.unwrap_or_default()
};
let r = self
- .teleport_inner(caller, req, PresenceAlready::NotConfirmed, None)
+ .teleport_inner(caller, req, PresenceAlready::NotConfirmed, None, false)
.await;
crate::telemetry::teleport(&self.telemetry, caller, &app, started, &r, items);
r
@@ -2470,6 +2509,7 @@ impl Broker {
req: TeleportRequest,
presence: PresenceAlready,
stage: Option<StageSink>,
+ launch: bool,
) -> Result<TeleportOutcome> {
validate_target(&req.target)?;
if req.items.is_empty() {
@@ -2697,6 +2737,18 @@ impl Broker {
let _ = self.backend.wipe(&req.target, &d.import_id).await;
}
let res = match &stage {
+ Some(sink) if launch => {
+ self.backend
+ .deliver_launching(
+ &req.target,
+ &provider,
+ payloads,
+ expires_ms,
+ sink.clone(),
+ true,
+ )
+ .await
+ }
Some(sink) => {
self.backend
.deliver_with_progress(
@@ -2708,6 +2760,18 @@ impl Broker {
)
.await
}
+ None if launch => {
+ self.backend
+ .deliver_launching(
+ &req.target,
+ &provider,
+ payloads,
+ expires_ms,
+ Arc::new(|_| {}),
+ true,
+ )
+ .await
+ }
None => {
self.backend
.deliver(&req.target, &provider, payloads, expires_ms)
diff --git a/libs/cua/crates/cua-keyvault/src/ipc.rs b/libs/cua/crates/cua-keyvault/src/ipc.rs
index 2a80a64146..33be325a75 100644
--- a/libs/cua/crates/cua-keyvault/src/ipc.rs
+++ b/libs/cua/crates/cua-keyvault/src/ipc.rs
@@ -165,6 +165,10 @@ pub enum Request {
/// reply. Off for older clients, which read one reply per request.
#[serde(default)]
progress: bool,
+ /// Open the app in the Space after importing it. On unless a client
+ /// says otherwise (older clients never sent it).
+ #[serde(default = "default_true")]
+ launch: bool,
},
/// Wipe deliveries on a target.
Release {
@@ -371,9 +375,17 @@ pub async fn dispatch(broker: &Broker, caller: &CallerIdentity, req: Request) ->
Request::RemoveRule { id } => reply!(broker.remove_rule(caller, &id).await),
Request::Teleport(r) => reply!(broker.teleport(caller, r).await),
Request::ImportAndTeleport {
- spec, target, save, ..
+ spec,
+ target,
+ save,
+ launch,
+ ..
} => {
- reply!(broker.import_and_teleport(caller, spec, target, save).await)
+ reply!(
+ broker
+ .import_and_teleport_launching(caller, spec, target, save, launch, None)
+ .await
+ )
}
Request::Release { target } => reply!(broker.release(caller, &target).await),
Request::ListDeliveries => reply!(broker.list_deliveries(caller).await),
@@ -508,8 +520,11 @@ async fn handle(mut stream: tokio::net::UnixStream, broker: Arc<Broker>, policy:
target,
save,
progress: true,
+ launch,
}) => {
- match teleport_streaming(&mut stream, &broker, &caller, spec, target, save).await {
+ match teleport_streaming(&mut stream, &broker, &caller, spec, target, save, launch)
+ .await
+ {
Some(r) => r,
None => return,
}
@@ -541,12 +556,13 @@ async fn teleport_streaming(
spec: ImportSpec,
target: String,
save: bool,
+ launch: bool,
) -> Option<Response> {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<TeleportStage>();
let sink: StageSink = Arc::new(move |s| {
let _ = tx.send(s);
});
- let work = broker.import_and_teleport_with_progress(caller, spec, target, save, Some(sink));
+ let work = broker.import_and_teleport_launching(caller, spec, target, save, launch, Some(sink));
tokio::pin!(work);
let mut connected = true;
let mut sent = 0usize;
@@ -898,6 +914,7 @@ impl KeyvaultClient {
target,
save,
progress: false,
+ launch: true,
})
.await
}
@@ -908,6 +925,19 @@ impl KeyvaultClient {
spec: ImportSpec,
target: String,
save: bool,
+ on: impl FnMut(TeleportStage) + Send,
+ ) -> Result<TeleportOutcome> {
+ self.import_and_teleport_launching(spec, target, save, true, on)
+ .await
+ }
+ /// [`Self::import_and_teleport_with_progress`] with an explicit `launch`
+ /// (whether the Space opens the app once it is imported).
+ pub async fn import_and_teleport_launching(
+ &mut self,
+ spec: ImportSpec,
+ target: String,
+ save: bool,
+ launch: bool,
mut on: impl FnMut(TeleportStage) + Send,
) -> Result<TeleportOutcome> {
let v = self
@@ -917,6 +947,7 @@ impl KeyvaultClient {
target,
save,
progress: true,
+ launch,
},
&mut on,
)
@@ -1135,6 +1166,7 @@ mod tests {
old,
Request::ImportAndTeleport {
progress: false,
+ launch: true,
..
}
));
@@ -1192,3 +1224,7 @@ mod tests {
}
}
}
+
+fn default_true() -> bool {
+ true
+}
diff --git a/libs/cua/crates/cua-keyvault/tests/broker.rs b/libs/cua/crates/cua-keyvault/tests/broker.rs
index b52f4a9512..ef16a15fc8 100644
--- a/libs/cua/crates/cua-keyvault/tests/broker.rs
+++ b/libs/cua/crates/cua-keyvault/tests/broker.rs
@@ -26,6 +26,8 @@ struct FakeBackend {
delivered: Mutex<Vec<(String, String, Vec<String>, u64)>>,
wiped: Mutex<Vec<(String, String)>>,
notified: Mutex<Vec<String>>,
+ /// The `launch` flag of every launching delivery.
+ launches: Mutex<Vec<bool>>,
captures: Mutex<Vec<ImportSpec>>,
/// Name -> immutable Space id. A name absent here resolves to a stable
/// `sandbox-<name>`; a test can insert a new id to model a rename or a
@@ -172,6 +174,23 @@ impl Backend for FakeBackend {
.await
}
+ async fn deliver_launching(
+ &self,
+ target: &str,
+ provider_id: &str,
+ payloads: Vec<ItemPayload>,
+ expires_ms: u64,
+ stage: cua_keyvault::broker::StageSink,
+ launch: bool,
+ ) -> cua_keyvault::Result<DeliveryOutcome> {
+ self.launches.lock().unwrap().push(launch);
+ let mut out = self
+ .deliver_with_progress(target, provider_id, payloads, expires_ms, stage)
+ .await?;
+ out.launched = launch;
+ Ok(out)
+ }
+
async fn wipe(&self, target: &str, import_id: &str) -> cua_keyvault::Result<Vec<String>> {
self.wiped
.lock()
@@ -1742,6 +1761,36 @@ async fn import_and_teleport_reports_its_stages_in_order() {
}
}
+/// A direct teleport opens the app in the Space (and says so), unless the
+/// caller asked not to; the grant-gated agent path never launches anything.
+#[tokio::test]
+async fn import_and_teleport_launches_the_app_unless_told_not_to() {
+ let r = rig().await;
+ let spec = || ImportSpec {
+ app: "chrome".into(),
+ sites: vec![SiteChoice {
+ site: "github.com".into(),
+ include_storage: false,
+ include_passwords: false,
+ }],
+ ..Default::default()
+ };
+ let on = r
+ .broker
+ .import_and_teleport(&r.cua, spec(), "dev-1".into(), false)
+ .await
+ .unwrap();
+ assert!(on.deliveries[0].launched);
+ let off = r
+ .broker
+ .import_and_teleport_launching(&r.cua, spec(), "dev-1".into(), false, false, None)
+ .await
+ .unwrap();
+ assert!(!off.deliveries[0].launched);
+ // Only the first asked for a launching delivery.
+ assert_eq!(*r.backend.launches.lock().unwrap(), vec![true]);
+}
+
/// `import_and_teleport` is what a direct (non-MCP) teleport uses instead of
/// exporting and uploading on its own: one first-party call, one presence
/// prompt, capture AND delivery both happen, and (save: true) the item stays
diff --git a/libs/cua/crates/cua-spaces-cli/src/teleport.rs b/libs/cua/crates/cua-spaces-cli/src/teleport.rs
index 629f33f0b5..206d6ece26 100644
--- a/libs/cua/crates/cua-spaces-cli/src/teleport.rs
+++ b/libs/cua/crates/cua-spaces-cli/src/teleport.rs
@@ -222,7 +222,7 @@ async fn push_through_keyvault(
))
})?;
let outcome = client
- .import_and_teleport(spec, sandbox.to_string(), false)
+ .import_and_teleport_launching(spec, sandbox.to_string(), false, !args.no_launch, |_| {})
.await
.map_err(|e| CuaError::PermissionDenied(format!("{}: {e}", manifest.provider_id)))?;
let delivery = outcome.deliveries.first().cloned().unwrap_or_default();
diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
index 93cf0ebf15..c9bf618731 100644
--- a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs
@@ -535,6 +535,21 @@ impl Backend for DaemonBackend {
payloads: Vec<ItemPayload>,
expires_ms: u64,
stage: cua_keyvault::broker::StageSink,
+ ) -> KvResult<DeliveryOutcome> {
+ self.deliver_launching(target, provider_id, payloads, expires_ms, stage, false)
+ .await
+ }
+
+ /// [`Self::deliver_with_progress`], with the receiver launching the app
+ /// afterwards (`launch`) and reporting whether it did.
+ async fn deliver_launching(
+ &self,
+ target: &str,
+ provider_id: &str,
+ payloads: Vec<ItemPayload>,
+ expires_ms: u64,
+ stage: cua_keyvault::broker::StageSink,
+ launch: bool,
) -> KvResult<DeliveryOutcome> {
let space = self.open_target(target).await?;
stage(TeleportStage::Packing);
@@ -583,7 +598,7 @@ impl Backend for DaemonBackend {
BundleSource::Bytes(&bytes),
&sha,
&SendOptions {
- launch_after: false,
+ launch_after: launch,
expires_at_ms: expires_ms,
// Every delivery through here was authorized by the broker.
broker_grant: Some("keyvault".into()),
diff --git a/libs/cua/crates/cua-spaces-ext/src/teleport.rs b/libs/cua/crates/cua-spaces-ext/src/teleport.rs
index d814cce320..39a525ba7e 100644
--- a/libs/cua/crates/cua-spaces-ext/src/teleport.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/teleport.rs
@@ -634,9 +634,9 @@ impl SpaceTeleport for Space {
// reported back as "not supported by this driver" --
// `cua-spacesd-server`'s `services/teleport.rs`), so routing
// through the Keyvault changes nothing about them. `launch_after`
- // is likewise not threaded through [`Backend::deliver`] yet (every
- // Keyvault-routed delivery, including the MCP paths, has the same
- // gap): the app lands but is not auto-launched. `relay_plaintext_ack`
+ // is threaded through the Keyvault's `import_and_teleport` (the
+ // receiver launches the app in the Space's GUI session and the
+ // receipt reports whether it did). `relay_plaintext_ack`
// (S1) is the direct upload path's own concern -- it answers
// whether *this* connection crosses an unsealed relay
// (`self.spacesd()`); the Keyvault's own delivery is a separate
@@ -689,10 +689,11 @@ impl SpaceTeleport for Space {
),
})?;
let outcome = client
- .import_and_teleport_with_progress(
+ .import_and_teleport_launching(
spec,
self.id().to_string(),
options.save_to_keyvault,
+ options.launch_after,
stage,
)
.await
@@ -707,7 +708,7 @@ impl SpaceTeleport for Space {
bundle_sha256: String::new(),
imported: delivery.map(|d| d.imported.clone()).unwrap_or_default(),
skipped: delivery.map(|d| d.skipped.clone()).unwrap_or_default(),
- launched: false,
+ launched: delivery.is_some_and(|d| d.launched),
})
}
}
@@ -806,7 +807,14 @@ pub(crate) async fn tool(
None => current.approving_default(&target, a.acknowledge_sensitive)?,
};
let receipt = s
- .teleport(sessions, &approval, ImportOptions::default())
+ .teleport(
+ sessions,
+ &approval,
+ ImportOptions {
+ launch_after: true,
+ ..ImportOptions::default()
+ },
+ )
.await?;
Ok(ToolOutcome::json(&receipt))
}
diff --git a/libs/cua/crates/cua-teleport-bundle/src/layout.rs b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
index 8cbdc898f0..e969a91d78 100644
--- a/libs/cua/crates/cua-teleport-bundle/src/layout.rs
+++ b/libs/cua/crates/cua-teleport-bundle/src/layout.rs
@@ -124,22 +124,40 @@ 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).
+ /// The cookie store of a Chromium-family profile directory. Chrome 96
+ /// moved it to `Network/Cookies`; current Chrome (154) reads `Cookies` in
+ /// the profile root again, so neither location is privileged. When both
+ /// exist (a profile that crossed versions) the one written most recently
+ /// wins, counting its `-wal` file, since a live Chrome's latest rows sit
+ /// there; a tie goes to the root file. With one, that one; with neither,
+ /// the root path (what current Chrome would create). Applies to every
+ /// profile and every Chromium-family browser.
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
+ let root = profile_dir.join("Cookies");
+ match (network.is_file(), root.is_file()) {
+ (true, true) => {
+ if last_written(&network) > last_written(&root) {
+ network
+ } else {
+ root
+ }
+ }
+ (true, false) => network,
+ _ => root,
}
}
+ /// Newest mtime of a SQLite database and its `-wal` sidecar.
+ fn last_written(db: &std::path::Path) -> Option<std::time::SystemTime> {
+ let mut wal = db.as_os_str().to_owned();
+ wal.push("-wal");
+ [db.to_path_buf(), std::path::PathBuf::from(wal)]
+ .iter()
+ .filter_map(|p| p.metadata().and_then(|m| m.modified()).ok())
+ .max()
+ }
+
/// 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 2a5acdacae..aeb2b4e3e9 100644
--- a/libs/cua/crates/cua-teleport/src/browser_cookies.rs
+++ b/libs/cua/crates/cua-teleport/src/browser_cookies.rs
@@ -185,7 +185,7 @@ 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()?;
- // `Default/Network/Cookies` first (Chrome 96+), then `Default/Cookies`.
+ // `Default/Cookies` or `Default/Network/Cookies`, whichever is newer.
let db = cua_teleport_bundle::layout::chrome::cookies_store(&dir);
if !db.is_file() {
return Err(TeleportError::Provider(format!(
@@ -538,14 +538,41 @@ mod tests {
assert_eq!(read_linux(&profile).unwrap().len(), 1);
}
- /// Both exist (a profile Chrome migrated): the modern one is read.
+ fn touch(path: &std::path::Path, secs_ago: u64) {
+ let t = std::time::SystemTime::now() - std::time::Duration::from_secs(secs_ago);
+ std::fs::File::options()
+ .write(true)
+ .open(path)
+ .unwrap()
+ .set_modified(t)
+ .unwrap();
+ }
+
+ /// Both exist: the newer one is read, in either direction.
#[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);
+ fn reads_the_newer_of_two_cookie_stores() {
+ for network_newer in [true, false] {
+ 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();
+ if !network_newer {
+ // Swap the contents: the root file holds the row and is newer.
+ std::fs::remove_dir_all(profile.join("Network")).unwrap();
+ std::fs::remove_file(profile.join("Cookies")).unwrap();
+ write_network_cookies_db_for_tests(&profile, &[]).unwrap();
+ write_cookies_db_for_tests(&profile, &one_row()).unwrap();
+ }
+ let (new, old) = if network_newer {
+ (profile.join("Network/Cookies"), profile.join("Cookies"))
+ } else {
+ (profile.join("Cookies"), profile.join("Network/Cookies"))
+ };
+ touch(&old, 600);
+ touch(&new, 5);
+ let got = read_linux(&profile).unwrap();
+ assert_eq!(got.len(), 1, "network_newer={network_newer}");
+ }
}
/// Chrome is running: its newest cookies are only in the `-wal` file. The
@@ -580,15 +607,26 @@ mod tests {
}
#[test]
- fn cookies_store_prefers_network_and_falls_back_to_legacy() {
+ fn cookies_store_picks_by_mtime_wal_included() {
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"));
+ // Neither: the root path, what current Chrome creates.
+ assert_eq!(cookies_store(p), p.join("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();
+ touch(&p.join("Cookies"), 600);
+ touch(&p.join("Network/Cookies"), 5);
+ assert_eq!(cookies_store(p), p.join("Network/Cookies"));
+ touch(&p.join("Cookies"), 1);
+ touch(&p.join("Network/Cookies"), 600);
+ assert_eq!(cookies_store(p), p.join("Cookies"));
+ // A fresh -wal on the network store makes it the live one.
+ std::fs::write(p.join("Network/Cookies-wal"), b"x").unwrap();
+ touch(&p.join("Network/Cookies-wal"), 0);
+ touch(&p.join("Cookies"), 100);
assert_eq!(cookies_store(p), p.join("Network/Cookies"));
}
diff --git a/libs/cua/crates/cua-teleport/src/providers/chrome.rs b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
index 0a61b98df0..76c3ab7c0b 100644
--- a/libs/cua/crates/cua-teleport/src/providers/chrome.rs
+++ b/libs/cua/crates/cua-teleport/src/providers/chrome.rs
@@ -455,7 +455,7 @@ 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
+/// whichever of `Network/Cookies` and the root file is newer; every
/// other file is at the profile root.
fn profile_file_path(profile_dir: &Path, name: &str) -> PathBuf {
if name == "Cookies" {
diff --git a/libs/images/macos/files/sanitize-guest.sh b/libs/images/macos/files/sanitize-guest.sh
index 4494aedf0e..245bdf9330 100755
--- a/libs/images/macos/files/sanitize-guest.sh
+++ b/libs/images/macos/files/sanitize-guest.sh
@@ -34,6 +34,52 @@ if [ -f "$NDB" ]; then
drop_btm_alerts
fi
+# The login keychain must take the account password ("lume"), or no installed
+# secret can ever be pre-authorized for its app: teleporting Chrome's session
+# raises "Google Chrome wants to access key 'Chrome Safe Storage' ... enter the
+# 'login' keychain password" in an unattended Space, and cua-spacesd's
+# `set-generic-password-partition-list -k lume` fails with "passphrase you
+# entered is not correct". Cause: /etc/kcpassword (the autologin password) is
+# the password XOR a fixed 11-byte key, and the plaintext must be NUL-padded
+# to a multiple of 12 BEFORE the XOR. lume's offline patcher XOR'd first and
+# appended raw zeroes, so loginwindow decodes the password as "lume" plus
+# garbage, cannot unlock the login keychain at autologin, moves it aside
+# (login_renamed_N.keychain-db, every boot) and makes a replacement keyed to
+# a passphrase nobody knows. Autologin itself still works, so nothing looks
+# broken. Rewrite the file correctly and give the login keychain the account
+# password; safe here, at build time, because the guest shuts down right
+# after (swapping a keychain under a live session leaves the session holding
+# a different, locked one). Same repair as the Spaces golden image.
+/usr/bin/python3 - >/tmp/kcpassword.new <<'KCP'
+import sys
+key = bytes.fromhex("7d895223d2bcddeaa3b91f")
+pw = b"lume"
+padded = pw + b"\x00" * (12 - len(pw) % 12)
+sys.stdout.buffer.write(bytes(b ^ key[i % len(key)] for i, b in enumerate(padded)))
+KCP
+sudo_run /bin/cp /tmp/kcpassword.new /etc/kcpassword
+sudo_run /usr/sbin/chown root:wheel /etc/kcpassword
+sudo_run /bin/chmod 600 /etc/kcpassword
+rm -f /tmp/kcpassword.new
+KC="$HOME/Library/Keychains"
+rm -f "$KC/login.keychain-db"* "$KC"/login_renamed_*.keychain-db "$KC/cua.keychain-db"*
+security create-keychain -p lume "$KC/login.keychain-db"
+security default-keychain -d user -s "$KC/login.keychain-db"
+security list-keychains -d user -s "$KC/login.keychain-db"
+security unlock-keychain -p lume "$KC/login.keychain-db"
+security set-keychain-settings "$KC/login.keychain-db"
+# Prove it takes the password (unlock-keychain on an unlocked keychain proves
+# nothing; only a command that takes -k checks it).
+security add-generic-password -U -s cua-keychain-probe -a probe -w x -A "$KC/login.keychain-db" 2>/dev/null
+if security set-generic-password-partition-list -S "apple:,apple-tool:" -k lume \
+ -s cua-keychain-probe -a probe "$KC/login.keychain-db" >/dev/null 2>&1; then
+ echo "login keychain takes the account password"
+else
+ echo "WARNING: the login keychain does not take the account password; teleported app keys will prompt" >&2
+fi
+security delete-generic-password -s cua-keychain-probe -a probe "$KC/login.keychain-db" >/dev/null 2>&1
+security unlock-keychain -p lume "$KC/login.keychain-db"
+
left=""
[ -z "$(ls -A "$HOME/.cua/spacesd")" ] || left="$left ~/.cua/spacesd/*"
[ ! -e /etc/cua/env-token ] || left="$left /etc/cua/env-token"