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): Chrome Safe Storage without keychain prompts (#4470)

ddupont5e4738bff890
diff --git a/docs/content/docs/spaces/guides/teleport-an-app.mdx b/docs/content/docs/spaces/guides/teleport-an-app.mdx
index 79c797cf29..446e9d8d36 100644
--- a/docs/content/docs/spaces/guides/teleport-an-app.mdx
+++ b/docs/content/docs/spaces/guides/teleport-an-app.mdx
@@ -125,24 +125,41 @@ drag-payload helpers over a `TeleportHost` you provide.
## The `cua` keychain on macOS Spaces
Chrome and other Chromium browsers keep their cookie key ("Safe Storage") in
-the Keychain. Session teleport installs that key into the Space's login
-keychain and pre-authorizes the browser. When the login keychain's password
-is not one the Space knows, cua-spacesd keeps the key in its own keychain,
-`~/Library/Keychains/cua.keychain-db`, instead. It behaves like this so that
-no password dialog ever appears in a Space nobody is watching:
-
-- The `cua` keychain is on the keychain search list, after the login keychain.
- It is not the default keychain, so system services such as Spotlight do not
- reach for it.
+the Keychain. Session teleport installs that key into a keychain that
+cua-spacesd owns, `~/Library/Keychains/cua.keychain-db`, and pre-authorizes
+the browser there. It never reads, writes or deletes anything in the Space's
+login keychain, so no password dialog ever appears in a Space nobody is
+watching, whether or not the browser was opened in the Space first:
+
+- The login keychain of a Lume image can have a password nobody knows (the
+ image's autologin file is padded wrong, so macOS re-keys the keychain at
+ every boot), and an item a browser made there trusts only that browser.
+ Reading it with `/usr/bin/security` raises "security wants to use your
+ confidential information stored in 'Chrome Safe Storage'" with nobody to
+ answer it.
+- The `cua` keychain is created with a password the Space knows and is the
+ **first** entry on the keychain search list. Browsers look their key up
+ through the search list and take the first match, so Chrome finds the key
+ teleport installed before any key it made itself. That key is left alone,
+ not read and not deleted. Cookies Chrome stored in the Space under its own
+ key before the teleport do not survive it; the teleport replaces the
+ session.
+- It is not the default keychain, so new items are not written there by other
+ apps.
- cua-spacesd unlocks it when it starts and again every 20 seconds, so it is
- open after a reboot and within seconds of a wake. The password comes from
- the Space's protected configuration (`CUA_ENV_LOGIN_KEYCHAIN_PW`,
+ open after a reboot and within seconds of a wake, and puts it back first on
+ the search list if something reset it. The password comes from the Space's
+ protected configuration (`CUA_ENV_LOGIN_KEYCHAIN_PW`,
`~/.cua/spacesd/keychain-password`, `/etc/cua/keychain-password`, then the
image's account password).
- It never auto-locks: no lock after a timeout and none on sleep
(`security set-keychain-settings` without `-l` or `-u`).
-- Most Spaces never create it: the Cua macOS image gives the login keychain
- the account password, so the key goes there.
+- Every `security` call has a 20 second deadline. A call that is stuck
+ behind a dialog is stopped, the dialog is dismissed, and the teleport fails
+ with an error that says so instead of hanging.
+- A running Chrome in the Space is quit before its profile is replaced and
+ opened again afterwards, so it reads the key teleport installed.
+- A Space that was never teleported into has no `cua` keychain.
## Session teleport
diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
index 3dc77a37b7..bbfa9d8c74 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/server.rs
@@ -550,6 +550,9 @@ pub async fn spawn_local(server: Server) -> std::io::Result<SocketAddr> {
/// wake, a timeout): see `cua_spacesd_teleport::keychain::keep_cua_keychain_unlocked`.
#[cfg(target_os = "macos")]
fn spawn_keychain_keeper(shutdown: tokio_util::sync::CancellationToken) {
+ // Nothing in an unattended Space can answer a Keychain dialog: have any
+ // Security API call made in this process fail instead of showing one.
+ cua_spacesd_teleport::keychain::forbid_keychain_prompts();
tokio::spawn(async move {
let host = cua_spacesd_teleport::default_host();
loop {
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 f892a46828..499d9ab003 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/cookies.rs
@@ -490,14 +490,14 @@ mod tests {
}
}
- fn keychain_fake() -> Arc<FakeHost> {
+ fn keychain_fake(home: &Path) -> Arc<FakeHost> {
// No pre-existing item: a secret READ (`find-generic-password ... -w`)
// fails, so `ensure_safe_storage_secret` takes the create path. Every
// other call -- the interactive `security -i` add, `install_generic`'s
// own post-install PRESENCE check (`find-generic-password` WITHOUT
// `-w`, attributes only), and `set-partition-list` -- succeeds, since
// those happen only after (and because) the item was just installed.
- Arc::new(FakeHost::new().with_responder(|c| {
+ Arc::new(FakeHost::new().with_home(home).with_responder(|c| {
if c.args.iter().any(|a| a == "find-generic-password")
&& c.args.iter().any(|a| a == "-w")
{
@@ -513,7 +513,7 @@ mod tests {
fn creates_a_fresh_key_when_none_exists_and_writes_readable_rows() {
let dir = tempfile::tempdir().unwrap();
let db_path = first_run_cookies_db(dir.path());
- let host = keychain_fake();
+ let host = keychain_fake(dir.path());
let items = vec![
item(".github.com", "user_session", "gh-session-abc"),
@@ -607,13 +607,21 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
first_run_cookies_db(dir.path());
let existing_secret = b"already-on-this-machine";
- let host = Arc::new(FakeHost::new().with_responder(move |c| {
- if c.args.iter().any(|a| a == "-w") {
- Ok(HostOutput::ok(existing_secret.to_vec()))
- } else {
- Ok(HostOutput::ok(""))
- }
- }));
+ // spacesd's own keychain, left by an earlier teleport.
+ let keychains = dir.path().join("Library/Keychains");
+ std::fs::create_dir_all(&keychains).unwrap();
+ std::fs::write(keychains.join("cua.keychain-db"), b"").unwrap();
+ let host = Arc::new(
+ FakeHost::new()
+ .with_home(dir.path())
+ .with_responder(move |c| {
+ if c.args.iter().any(|a| a == "-w") {
+ Ok(HostOutput::ok(existing_secret.to_vec()))
+ } else {
+ Ok(HostOutput::ok(""))
+ }
+ }),
+ );
let mut record = ImportRecord::default();
let secret = ensure_safe_storage_secret(
host.as_ref(),
@@ -794,7 +802,7 @@ mod tests {
#[test]
fn never_launched_profile_creates_the_keychain_key_on_macos() {
let dir = tempfile::tempdir().unwrap();
- let host = keychain_fake();
+ let host = keychain_fake(dir.path());
let mut record = ImportRecord::default();
install_cookies(
host.as_ref(),
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
index b667e28c5c..bf67c03c44 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/chrome.rs
@@ -24,6 +24,10 @@ use super::write_entry;
use crate::host::{default_host, HostEffects};
use crate::{ImportProvider, ImportRecord, Result};
+/// `pgrep -f` pattern for every process of the destination's Google Chrome
+/// (the main process and its helpers all live inside the bundle).
+const MACOS_PROCESS_PATTERN: &str = "Google Chrome.app/Contents/";
+
/// The Chrome/Chromium importer.
pub struct ChromeImporter {
max_total_bytes: u64,
@@ -76,6 +80,16 @@ impl ImportProvider for ChromeImporter {
record: &mut ImportRecord,
) -> Result<LaunchSpec> {
let mut reader = BundleReader::open_with_limit(bundle, self.max_total_bytes)?;
+ // Stop a running Chrome BEFORE touching its profile (macOS). A Chrome
+ // the user already opened in the Space (the usual case once it has been
+ // "opened once") holds the Cookies database open, caches the Safe
+ // Storage key it read at startup, and would keep serving its old
+ // signed-out session: the launch below is `open -a`, which only focuses
+ // an app that is already running. Quitting it makes the teleport land,
+ // and the relaunch read the key this import installed.
+ if platform == Platform::MacOS {
+ super::terminate_running(&*self.host, MACOS_PROCESS_PATTERN);
+ }
let mut tab_urls: Vec<String> = Vec::new();
let mut cookies_entry: Option<Vec<u8>> = None;
let mut local_storage_entry: Option<Vec<u8>> = None;
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
index d057c8fd95..8f7ccc3585 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/electron.rs
@@ -19,7 +19,7 @@ use cua_teleport_bundle::layout::electron::{
use cua_teleport_bundle::{LaunchSpec, Platform};
use super::write_entry;
-use crate::host::{default_host, EffectKind, HostCommand, HostEffects};
+use crate::host::{default_host, HostEffects};
use crate::keychain;
use crate::{ImportProvider, ImportRecord, Result};
@@ -88,7 +88,9 @@ impl ImportProvider for ElectronImporter {
// * the launch below is `open -a`, which merely focuses an app that is
// already running. The destination then keeps the signed-out session
// it started with.
- terminate_running(&*self.host, platform, self.app.display);
+ if let Some(pattern) = process_pattern(platform, self.app.display) {
+ super::terminate_running(&*self.host, &pattern);
+ }
record.create_dir_all(&dest_home.join(profile_dir(&self.app, platform)))?;
while let Some(entry) = reader.next_entry()? {
@@ -104,49 +106,10 @@ impl ImportProvider for ElectronImporter {
}
}
-/// Stop a running instance of the app so an import is not racing it and the
-/// following launch really starts it fresh. Best-effort: if nothing is running,
-/// or the platform has no matching mechanism, this is a no-op. Matching on the
-/// executable path inside the bundle keeps it from hitting unrelated processes
-/// that merely mention the app's name. Bounded: at most ~10 s of polling.
-fn terminate_running(host: &dyn HostEffects, platform: Platform, display: &str) {
- let Some(pattern) = process_pattern(platform, display) else {
- // pkill isn't available on Windows; the launcher replaces the process.
- return;
- };
- let running = || {
- host.run(&HostCommand::new(EffectKind::ProcessLookup, "pgrep").args(["-f", &pattern]))
- .map(|output| output.success)
- .unwrap_or(false)
- };
- if !running() {
- return;
- }
- let kill = |signal: &str| {
- let _ = host.run(
- &HostCommand::new(EffectKind::ProcessTerminate, "pkill").args([signal, "-f", &pattern]),
- );
- };
-
- // Ask politely, then WAIT for the process to actually be gone: an Electron
- // app shutting down gracefully writes its profile out as the last thing it
- // does, so an import that starts too early is overwritten by that flush.
- kill("-TERM");
- for _ in 0..40 {
- std::thread::sleep(std::time::Duration::from_millis(250));
- if !running() {
- return;
- }
- }
- // Refused to go quietly — take it down hard and let the filesystem settle.
- kill("-KILL");
- std::thread::sleep(std::time::Duration::from_millis(500));
-}
-
#[cfg(test)]
mod tests {
use super::*;
- use crate::host::{FakeHost, HostOutput};
+ use crate::host::{EffectKind, FakeHost, HostOutput};
use crate::importers::fixtures::bundle;
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -280,7 +243,7 @@ mod tests {
}]);
let dest = tempfile::tempdir().unwrap();
// Keychain commands succeed; no Slack is running.
- let host = Arc::new(FakeHost::new().with_responder(|c| {
+ let host = Arc::new(FakeHost::new().with_home(dest.path()).with_responder(|c| {
Ok(match c.kind {
EffectKind::ProcessLookup => HostOutput::failed(),
_ => HostOutput::ok(""),
diff --git a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/mod.rs b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/mod.rs
index db17574254..4ba90f0b35 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/mod.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/importers/mod.rs
@@ -15,9 +15,45 @@ use std::path::Path;
use cua_teleport_bundle::bundle::VerifiedEntry;
+use crate::host::{EffectKind, HostCommand, HostEffects};
use crate::ledger::ImportRecord;
use crate::Result;
+/// Stop a running instance of the app so an import is not racing it and the
+/// following launch really starts it fresh. Best-effort: if nothing is running,
+/// or the platform has no matching mechanism, this is a no-op. `pattern` is a `pgrep -f` pattern; matching on the
+/// executable path inside the bundle keeps it from hitting unrelated processes
+/// that merely mention the app's name. Bounded: at most ~10 s of polling.
+pub(crate) fn terminate_running(host: &dyn HostEffects, pattern: &str) {
+ let running = || {
+ host.run(&HostCommand::new(EffectKind::ProcessLookup, "pgrep").args(["-f", pattern]))
+ .map(|output| output.success)
+ .unwrap_or(false)
+ };
+ if !running() {
+ return;
+ }
+ let kill = |signal: &str| {
+ let _ = host.run(
+ &HostCommand::new(EffectKind::ProcessTerminate, "pkill").args([signal, "-f", pattern]),
+ );
+ };
+
+ // Ask politely, then WAIT for the process to actually be gone: an Electron
+ // app shutting down gracefully writes its profile out as the last thing it
+ // does, so an import that starts too early is overwritten by that flush.
+ kill("-TERM");
+ for _ in 0..40 {
+ std::thread::sleep(std::time::Duration::from_millis(250));
+ if !running() {
+ return;
+ }
+ }
+ // Refused to go quietly — take it down hard and let the filesystem settle.
+ kill("-KILL");
+ std::thread::sleep(std::time::Duration::from_millis(500));
+}
+
/// Write one verified bundle entry to `dest`, creating parent directories.
/// Unix permissions come from the entry (0600 when it carries none, or when
/// `owner_only` is set — credential blobs are always tightened). The file and
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 2c40d6daac..0341e6b964 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/src/keychain.rs
@@ -5,27 +5,142 @@
//!
//! Chromium/Electron apps (Chrome, Slack, Discord, …) encrypt their local
//! cookies and auth tokens with an app-specific **"Safe Storage"** key held in
-//! the login Keychain, and some keep their auth token there too. The sender
-//! reads those items and packs them into the reserved [`KEYCHAIN_ENTRY`];
+//! the Keychain, and some keep their auth token there too. The sender reads
+//! those items and packs them into the reserved [`KEYCHAIN_ENTRY`];
//! [`install_all`] reinstalls them in the destination's Keychain via
//! `security add-generic-password`, through the injected [`HostEffects`].
//! Non-macOS destinations install nothing (the functions are no-ops that
//! report it), so the crate still builds and runs everywhere.
+//!
+//! # Nothing here may ever raise a Keychain prompt
+//!
+//! A Space is unattended: a SecurityAgent dialog ("security wants to use your
+//! confidential information stored in 'Chrome Safe Storage'", "enter the
+//! 'login' keychain password") has nobody to answer it and blocks whatever
+//! asked, here the teleport, forever. The two ways this module used to raise
+//! one, both from touching the **login** keychain, are closed by design:
+//!
+//! * The login keychain of a Lume image does not take the account password
+//! (lume's offline `/etc/kcpassword` padding bug makes loginwindow re-key it
+//! to a passphrase nobody knows), and an item an app created there (Chrome's
+//! own `Chrome Safe Storage`) trusts only that app. Reading it with
+//! `/usr/bin/security` prompts; so does writing its partition list.
+//! * So spacesd never reads, writes, deletes or re-authorizes anything in the
+//! login keychain. Every item goes into a keychain spacesd **owns**
+//! (`cua.keychain-db`), created with a password spacesd knows and kept
+//! unlocked, which is put FIRST on the user's search list. Chromium looks its
+//! key up through the search list (`SecKeychainFindGenericPassword` with no
+//! keychain), which returns the first match, so the app finds ours before any
+//! item the login keychain holds, with no prompt: our item carries the app's
+//! code-signing team in its partition list and is readable by any app. A key
+//! the app made itself in the login keychain is shadowed, not read or
+//! deleted, so nothing of the user's is lost.
+//! * Every `security` call is bounded ([`SECURITY_TIMEOUT`]); if one still
+//! hangs on a dialog it is killed, the dialog is dismissed and the call fails
+//! with an error that says so, instead of hanging the teleport.
+//! * The spacesd process itself turns Keychain user interaction off
+//! ([`forbid_keychain_prompts`]) so an in-process Security API call fails
+//! with `errSecInteractionNotAllowed` rather than showing UI.
pub use cua_teleport_bundle::keychain::{KeychainItem, KEYCHAIN_ENTRY};
use crate::host::HostEffects;
#[cfg(target_os = "macos")]
-use crate::host::{EffectKind, HostCommand};
+use crate::host::{EffectKind, HostCommand, HostOutput};
use crate::ledger::ImportRecord;
-/// Reads a generic-password item's secret from the destination's own target
-/// keychain ([`target_keychain_path`]) -- never the search list, so this never
-/// picks up a same-named item some other keychain happens to hold. `None`
-/// when no such item exists there, or off macOS (nothing is ever installed
-/// there). Used to detect an already-initialized Safe Storage key (e.g. this
-/// guest's Chrome already ran once) so a re-encrypting import reuses it
-/// instead of minting a second, conflicting one.
+/// Upper bound on any one `security` invocation. Every call here is local and
+/// finishes in well under a second; one that takes this long is stuck behind a
+/// Keychain dialog nobody can answer.
+#[cfg(target_os = "macos")]
+pub const SECURITY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
+
+#[cfg(target_os = "macos")]
+#[link(name = "Security", kind = "framework")]
+extern "C" {
+ fn SecKeychainSetUserInteractionAllowed(state: u8) -> i32;
+}
+
+/// Turns Keychain user interaction off for THIS process: a Security API call
+/// that would have shown a SecurityAgent dialog fails with
+/// `errSecInteractionNotAllowed` instead. A Space is unattended, nothing could
+/// answer the dialog. (Child `security` processes are covered separately, by
+/// [`SECURITY_TIMEOUT`] and by never touching a keychain whose password this
+/// guest does not know.) A no-op off macOS.
+pub fn forbid_keychain_prompts() {
+ #[cfg(target_os = "macos")]
+ {
+ // SAFETY: a plain C call taking a Boolean; no pointers.
+ let _ = unsafe { SecKeychainSetUserInteractionAllowed(0) };
+ }
+}
+
+/// Runs one `security` invocation with a deadline. A call that hits it was
+/// stuck behind a Keychain dialog: kill the dialog too (it would otherwise sit
+/// on the screen forever; SecurityAgent ignores SIGTERM, so SIGKILL, and it is
+/// started again on demand) and say so.
+#[cfg(target_os = "macos")]
+fn security(
+ host: &dyn HostEffects,
+ kind: EffectKind,
+ args: Vec<String>,
+ stdin: Option<Vec<u8>>,
+) -> std::io::Result<HostOutput> {
+ let sub = args
+ .iter()
+ .find(|a| !a.starts_with('-'))
+ .cloned()
+ .unwrap_or_default();
+ let mut command = HostCommand::new(kind, "security")
+ .args(args)
+ .timeout(SECURITY_TIMEOUT);
+ if let Some(bytes) = stdin {
+ command = command.stdin(bytes);
+ }
+ match host.run(&command) {
+ Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
+ let _ = host.run(
+ &HostCommand::new(EffectKind::ProcessTerminate, "pkill").args([
+ "-KILL",
+ "-x",
+ "SecurityAgent",
+ ]),
+ );
+ Err(std::io::Error::new(
+ std::io::ErrorKind::TimedOut,
+ format!(
+ "`security {sub}` did not finish within {}s: it was waiting on a Keychain \
+ dialog that nothing in an unattended Space can answer, so it was stopped",
+ SECURITY_TIMEOUT.as_secs()
+ ),
+ ))
+ }
+ other => other,
+ }
+}
+
+/// `security` with plain `&str` arguments, reporting only whether it succeeded.
+#[cfg(target_os = "macos")]
+fn security_ok(host: &dyn HostEffects, kind: EffectKind, args: &[&str]) -> bool {
+ security(
+ host,
+ kind,
+ args.iter().map(|a| a.to_string()).collect(),
+ None,
+ )
+ .map(|o| o.success)
+ .unwrap_or(false)
+}
+
+/// Reads a generic-password item's secret from spacesd's OWN keychain
+/// (`cua.keychain-db`) -- never the login keychain or the search list.
+/// That keychain's password is known, so the read never prompts; the login
+/// keychain's is not, and an item an app created there trusts only that app, so
+/// reading it with `security` raises a dialog nobody can answer. `None` when no
+/// such item exists there (spacesd has not installed one yet), when the keychain
+/// cannot be opened, or off macOS. Used to reuse the key a previous teleport
+/// installed, so a re-teleport re-encrypts under the same key instead of minting
+/// a second, conflicting one.
pub fn read_generic(
host: &dyn HostEffects,
service: &str,
@@ -33,7 +148,7 @@ pub fn read_generic(
) -> Option<Vec<u8>> {
#[cfg(target_os = "macos")]
{
- let keychain = target_keychain_path(host).to_string_lossy().into_owned();
+ let keychain = existing_cua_keychain(host)?;
let mut args = vec![
"find-generic-password".to_string(),
"-s".to_string(),
@@ -45,9 +160,7 @@ pub fn read_generic(
}
args.push("-w".to_string());
args.push(keychain);
- let output = host
- .run(&HostCommand::new(EffectKind::KeychainRead, "security").args(args))
- .ok()?;
+ let output = security(host, EffectKind::KeychainRead, args, None).ok()?;
if !output.success {
return None;
}
@@ -68,9 +181,11 @@ pub fn read_generic(
}
}
-/// Remove a generic-password item (by service and account) from the target
-/// keychain and every keychain on the search list. Returns whether one was
-/// removed. Off macOS nothing was ever installed, so this is `Ok(false)`.
+/// Remove a generic-password item (by service and account) that spacesd
+/// installed, from spacesd's own keychain. Never touches the login keychain or
+/// any other: an item an app made there (Chrome's own Safe Storage key) is not
+/// ours to delete. Returns whether one was removed. Off macOS nothing was ever
+/// installed, so this is `Ok(false)`.
pub fn remove_generic(
host: &dyn HostEffects,
service: &str,
@@ -78,21 +193,23 @@ pub fn remove_generic(
) -> std::io::Result<bool> {
#[cfg(target_os = "macos")]
{
- let mut removed = false;
- for keychain in search_list_keychains(host) {
- let output = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security").args([
- "delete-generic-password",
- "-s",
- service,
- "-a",
- account,
- &keychain,
- ]),
- )?;
- removed |= output.success;
- }
- Ok(removed)
+ let Some(keychain) = existing_cua_keychain(host) else {
+ return Ok(false);
+ };
+ let output = security(
+ host,
+ EffectKind::KeychainWrite,
+ vec![
+ "delete-generic-password".into(),
+ "-s".into(),
+ service.into(),
+ "-a".into(),
+ account.into(),
+ keychain,
+ ],
+ None,
+ )?;
+ Ok(output.success)
}
#[cfg(not(target_os = "macos"))]
{
@@ -103,13 +220,11 @@ pub fn remove_generic(
/// Reads a generic-password item's secret from the DESTINATION's own
/// Keychain (this machine's, never the source's -- nothing in this crate ever
-/// receives a source secret to read). `None` when no such item exists yet
-/// (a fresh Space, or a browser that has not created its Safe Storage item
-/// on this machine). Used by [`crate::cookies::ensure_safe_storage_secret`]
-/// to tell "this destination already has its own key, use it" from "none
-/// exists, create one" -- the destination's re-encryption always uses a key
-/// that either already lived here or was generated here, never one carried
-/// on the wire.
+/// receives a source secret to read). `None` when spacesd has not installed one
+/// yet. Used by [`crate::cookies::ensure_safe_storage_secret`] to tell "a
+/// previous teleport already gave this app its key, reuse it" from "none exists,
+/// create one" -- the destination's re-encryption always uses a key that either
+/// already lived here or was generated here, never one carried on the wire.
pub fn read_secret(host: &dyn HostEffects, service: &str, account: &str) -> Option<Vec<u8>> {
read_generic(host, service, Some(account))
}
@@ -140,26 +255,24 @@ fn add_command_line(item: &KeychainItem, keychain: &str) -> std::io::Result<Stri
))
}
-/// Install one generic-password item into the login Keychain, first deleting
-/// any existing item with the same service+account so the write never needs
-/// authorization. Non-macOS is a no-op reporting success (there is nothing to
-/// install). Returns `Ok` on success.
+/// Install one generic-password item into spacesd's keychain. 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.
+/// about anything the user should know. Fails, fast and with a clear error,
+/// rather than leave an item the app would prompt for: a teleport that cannot
+/// install silently is a failed teleport, not a hung one.
///
-/// 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 joins the search list (never the default) and is kept
-/// unlocked by [`keep_cua_keychain_unlocked`], where the write succeeds and the
-/// app reads the key silently.
+/// The item goes into the keychain spacesd owns (`ensure_cua_keychain`):
+/// created with a password spacesd knows, unlocked, never auto-locked, and first
+/// on the search list so the app's own lookup finds it before anything the login
+/// keychain holds (see the module docs for why the login keychain is never
+/// used). The app is pre-authorized with a partition-list write using that known
+/// password, which succeeds, silently, every time.
pub fn install_generic_noted(
host: &dyn HostEffects,
item: &KeychainItem,
@@ -167,31 +280,19 @@ pub fn install_generic_noted(
) -> std::io::Result<()> {
#[cfg(target_os = "macos")]
{
- let keychain = target_keychain_path(host).to_string_lossy().into_owned();
- 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 _ = &notes;
+ let keychain = ensure_cua_keychain(host)?;
+ if !install_into(host, item, &keychain)? {
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"
- ));
+ return Err(std::io::Error::other(format!(
+ "could not pre-authorize {app} to read its saved key from {keychain}; {app} \
+ would raise a Keychain prompt nobody in this Space can answer, so the \
+ teleport was stopped instead"
+ )));
}
- ensure_login_unlocked(host);
Ok(())
}
#[cfg(not(target_os = "macos"))]
@@ -201,123 +302,84 @@ pub fn install_generic_noted(
}
}
-/// 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.
+/// Adds `item` to spacesd's `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 might 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,
- ]),
- );
- }
+ // Delete this service+account from OUR keychain first, rather than
+ // replacing it with `-U`: updating an item the caller does not own needs
+ // authorization (an unanswerable dialog in a Space). Creating a fresh item
+ // never prompts. Only our own keychain is touched: an item the app made
+ // itself in the login keychain trusts only that app, is not ours to delete,
+ // and does not need to be -- our keychain is first on the search list, so
+ // the app's lookup finds ours and never reaches it.
+ let _ = security(
+ host,
+ EffectKind::KeychainWrite,
+ vec![
+ "delete-generic-password".into(),
+ "-s".into(),
+ item.service.clone(),
+ "-a".into(),
+ item.account.clone(),
+ keychain.to_string(),
+ ],
+ None,
+ )?;
- // 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.
+ // The secret never goes on argv: argv is readable by every local user
+ // (`ps`). `security -i` reads commands from stdin instead, and the value
+ // travels hex-encoded (`-X`, see security(1) add-generic-password).
//
- // `-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.
+ // `-A`: every application may read this item without an "allow access?"
+ // prompt. `-T <app>` looks tighter but is matched against the *reading*
+ // process, which for an Electron app 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, the
+ // keychain is spacesd's own, and anything that could read the item could
+ // equally read the profile it decrypts.
let line = add_command_line(item, keychain)?;
- let output = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security")
- .args(["-q", "-i"])
- .stdin(line.into_bytes()),
+ let output = security(
+ host,
+ EffectKind::KeychainWrite,
+ vec!["-q".into(), "-i".into()],
+ Some(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).
+ // 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);
+ && security(
+ host,
+ EffectKind::KeychainRead,
+ vec![
+ "find-generic-password".into(),
+ "-s".into(),
+ item.service.clone(),
+ "-a".into(),
+ item.account.clone(),
+ keychain.to_string(),
+ ],
+ None,
+ )
+ .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.
+ // macOS also gates reads on the item's PARTITION LIST, independently of the
+ // ACL. An item created by `security` gets `apple-tool:`, which excludes
+ // every app that is not an Apple command-line tool: without the app's
+ // code-signing team in it the app gets "<App> wants to access key ... enter
+ // the keychain password". ALWAYS set it, with the team when known.
let team = item
.trust_app
.as_deref()
@@ -330,17 +392,11 @@ fn install_into(
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);
+ // `set-generic-password-partition-list -k` unlocks the keychain for the
+ // call and RE-LOCKS it on the way out. A locked keychain on the search list
+ // makes any process that reaches for it (Spotlight's mdworker is one)
+ // raise "<Process> wants to use the '<keychain>' keychain".
+ keep_unlocked(host, keychain);
Ok(authorized)
}
@@ -358,28 +414,27 @@ pub fn install_all_recorded(
bytes: &[u8],
record: &mut ImportRecord,
) -> usize {
- #[cfg(target_os = "macos")]
- ensure_login_unlocked(host);
let items = cua_teleport_bundle::keychain::parse(bytes);
- let installed = items
+ items
.iter()
.filter(|item| {
- let ok = install_generic_noted(host, item, &mut record.notices).is_ok();
+ let ok = match install_generic_noted(host, item, &mut record.notices) {
+ Ok(()) => true,
+ Err(e) => {
+ eprintln!(
+ "teleport: keychain item {:?} not installed: {e}",
+ item.service
+ );
+ record.notices.push(format!("{}: {e}", item.service));
+ false
+ }
+ };
if ok && cfg!(target_os = "macos") {
record.keychain_installed(&item.service, &item.account);
}
ok
})
- .count();
- // AGAIN, afterwards. `security` commands that take `-k <password>` — which
- // is every partition-list write above — unlock the keychain for the call
- // and RE-LOCK it when they finish. Leaving it locked is not a silent
- // detail: the app we just installed credentials for launches next and gets
- // "<App> wants to use the '<keychain>' keychain", a SecurityAgent dialog
- // that nothing in an unattended destination can answer.
- #[cfg(target_os = "macos")]
- ensure_login_unlocked(host);
- installed
+ .count()
}
/// The code-signing Team Identifier of an installed `.app`, e.g. "9QW8UQUTAA"
@@ -454,7 +509,7 @@ fn set_partition_list(
args.push(account.to_string());
}
args.push(path.to_string_lossy().into_owned());
- match host.run(&HostCommand::new(EffectKind::KeychainWrite, "security").args(args)) {
+ match security(host, EffectKind::KeychainWrite, args, None) {
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(),
@@ -528,262 +583,197 @@ pub(crate) fn trusted_app_for(service: &str) -> Option<&'static str> {
}
}
-/// Where spacesd's own keychain lives.
+/// Where spacesd's own keychain lives (`CUA_ENV_KEYCHAIN` overrides it for a
+/// provisioner that brings its own, already unlocked).
#[cfg(target_os = "macos")]
fn cua_keychain_path(host: &dyn HostEffects) -> Option<std::path::PathBuf> {
+ if let Some(p) = std::env::var_os("CUA_ENV_KEYCHAIN") {
+ let p = std::path::PathBuf::from(p);
+ if !p.as_os_str().is_empty() {
+ return Some(p);
+ }
+ }
Some(host.home_dir()?.join("Library/Keychains/cua.keychain-db"))
}
/// Unlocks `path` with the first of `passwords` it takes and gives it no
/// auto-lock: `set-keychain-settings` without `-l` (lock on sleep) or `-u`
/// (lock after a timeout) leaves it open until logout. Whether it opened.
+/// `unlock-keychain -p` is non-interactive by construction: with a password
+/// given it either opens the keychain or fails, it never shows a dialog.
#[cfg(target_os = "macos")]
fn unlock_and_unlimit(host: &dyn HostEffects, path: &str, passwords: &[String]) -> bool {
let mut opened = false;
for pw in passwords {
- let ok = host
- .run(
- &HostCommand::new(EffectKind::KeychainWrite, "security")
- .args(["unlock-keychain", "-p", pw, path])
- .timeout(std::time::Duration::from_secs(20)),
- )
- .map(|o| o.success)
- .unwrap_or(false);
- if ok {
+ if security_ok(
+ host,
+ EffectKind::KeychainWrite,
+ &["unlock-keychain", "-p", pw, path],
+ ) {
opened = true;
break;
}
}
if opened {
- let _ = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security")
- .args(["set-keychain-settings", path])
- .timeout(std::time::Duration::from_secs(20)),
+ security_ok(
+ host,
+ EffectKind::KeychainWrite,
+ &["set-keychain-settings", path],
);
}
opened
}
-/// Unlocks spacesd's `cua` keychain (the fallback home of Chrome's Safe
-/// Storage key when the login keychain's password is unknown) and keeps it
-/// from locking. A locked keychain on the search list makes whatever touches
-/// it raise "<App> wants to use the 'cua' keychain. Please enter the
-/// keychain password.", which nobody can answer in an unattended Space. It
-/// locks again when the Space reboots (the lock is not persistent) and a
-/// keychain created with the defaults locks on sleep and after a timeout, so
-/// spacesd calls this at start-up and then every [`KEEPER_INTERVAL`], which
-/// also covers wake from sleep. The password is the one from spacesd's
-/// protected config (`CUA_ENV_LOGIN_KEYCHAIN_PW`, `~/.cua/spacesd/keychain-password`,
-/// `/etc/cua/keychain-password`, then the image's `lume`). Does nothing when
-/// the keychain does not exist (the login keychain took the password, the
-/// usual case) or off macOS. Returns whether the keychain is now open.
-pub fn keep_cua_keychain_unlocked(host: &dyn HostEffects) -> bool {
- #[cfg(target_os = "macos")]
- {
- let Some(path) = cua_keychain_path(host) else {
- return false;
- };
- if !path.exists() {
- return false;
- }
- unlock_and_unlimit(host, &path.to_string_lossy(), &keychain_passwords(host))
- }
- #[cfg(not(target_os = "macos"))]
- {
- let _ = host;
- false
- }
+/// Re-opens `keychain` (a keychain spacesd owns) with the passwords this guest
+/// knows. Cheap and silent; called after anything that re-locks it.
+#[cfg(target_os = "macos")]
+fn keep_unlocked(host: &dyn HostEffects, keychain: &str) {
+ unlock_and_unlimit(host, keychain, &keychain_passwords(host));
}
-/// How often [`keep_cua_keychain_unlocked`] runs in the daemon: the longest
-/// the keychain stays locked after a wake.
-pub const KEEPER_INTERVAL: std::time::Duration = std::time::Duration::from_secs(20);
-
-/// Makes sure a keychain whose password this guest knows exists, is unlocked,
-/// never auto-locks and is on the search list (not the default), and returns
-/// its path. `None` when it cannot be created or opened.
+/// spacesd's keychain when it already exists on disk and opens with a password
+/// this guest knows; `None` otherwise (nothing to read from, and nothing here
+/// may create one: that is [`ensure_cua_keychain`]'s job).
#[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;
- }
- // Open and never auto-lock (see [`keep_cua_keychain_unlocked`]).
- if !unlock_and_unlimit(host, &path_str, std::slice::from_ref(&pw)) {
+fn existing_cua_keychain(host: &dyn HostEffects) -> Option<String> {
+ let path = cua_keychain_path(host)?;
+ if !path.exists() {
return None;
}
- // On the search list (apps read through it), AFTER the login keychain
- // and the rest, which stay as they were. It is deliberately NOT the
- // default keychain: system services (Spotlight's mdworker above all)
- // reach for the default, and any moment it is locked they raise
- // "<Process> wants to use the 'cua' keychain", a dialog nothing in an
- // unattended Space can answer. Chrome finds its Safe Storage key
- // through the search list.
- let mut list: Vec<String> = Vec::new();
- 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);
- }
- }
- }
- if !list.contains(&path_str) {
- list.push(path_str.clone());
- let mut args = vec![
- "list-keychains".to_string(),
- "-d".into(),
- "user".into(),
- "-s".into(),
- ];
- args.extend(list);
- sec(args);
- }
- Some(path_str)
+ let path = path.to_string_lossy().into_owned();
+ unlock_and_unlimit(host, &path, &keychain_passwords(host)).then_some(path)
}
-/// The keychain teleported items are installed into.
+/// Makes sure spacesd's own keychain exists, is unlocked and never auto-locks,
+/// and is FIRST on the user's keychain search list, and returns its path.
///
-/// `CUA_ENV_KEYCHAIN` names it explicitly, which is what an unattended
-/// destination should do: the login keychain macOS creates at login has a
-/// password we cannot reproduce, so the partition-list write below fails on
-/// it, and making a keychain we *did* create the DEFAULT instead redirects
-/// Spotlight and other system agents into it — both end in a SecurityAgent
-/// dialog nobody can answer. Naming one keychain keeps the default alone.
-/// Falls back to the default keychain, then to the login keychain.
-#[cfg(target_os = "macos")]
-/// Every user keychain on the search list, plus our explicit target, as paths.
+/// Created with the first of [`keychain_passwords`], so it always takes a
+/// password this guest knows (unlike the login keychain of an image with the
+/// autologin-password bug). If one exists that takes none of them (corrupt, or
+/// re-keyed by something else) it is set aside as `cua.keychain-db.unusable`
+/// (never deleted) and replaced: it only ever held items spacesd itself can
+/// install again.
///
-/// `security list-keychains` prints them quoted, one per line. The target is
-/// included even if it is not (yet) on the list, so a fresh keychain is still
-/// cleaned.
-fn search_list_keychains(host: &dyn HostEffects) -> Vec<String> {
- let mut out = vec![target_keychain_path(host).to_string_lossy().into_owned()];
- 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 path = line.trim().trim_matches('"').to_string();
- if !path.is_empty() && !out.contains(&path) {
- out.push(path);
- }
+/// First on the list, because Chromium and Electron apps look their Safe
+/// Storage key up through the search list and take the first match. That is
+/// what makes an item the app created in the login keychain irrelevant: ours
+/// wins, silently.
+#[cfg(target_os = "macos")]
+fn ensure_cua_keychain(host: &dyn HostEffects) -> std::io::Result<String> {
+ let path = cua_keychain_path(host)
+ .ok_or_else(|| std::io::Error::other("this Space has no home directory"))?;
+ let path_str = path.to_string_lossy().into_owned();
+ let passwords = keychain_passwords(host);
+ let usable = path.exists() && unlock_and_unlimit(host, &path_str, &passwords);
+ if !usable {
+ if path.exists() {
+ eprintln!(
+ "teleport: {path_str} takes no password this Space knows; setting it aside and \
+ creating a new one"
+ );
+ set_aside(&path);
+ }
+ // `?`: a call stuck behind a dialog says so (see `security`), rather than
+ // being reported as a keychain that merely could not be created.
+ let created = security(
+ host,
+ EffectKind::KeychainWrite,
+ vec![
+ "create-keychain".into(),
+ "-p".into(),
+ passwords.first().cloned().unwrap_or_else(|| "lume".into()),
+ path_str.clone(),
+ ],
+ None,
+ )?
+ .success;
+ if !created || !unlock_and_unlimit(host, &path_str, &passwords) {
+ return Err(std::io::Error::other(format!(
+ "could not create or open the keychain {path_str} that Cua uses to hand \
+ saved browser keys to apps"
+ )));
}
}
- out
+ put_first_on_search_list(host, &path_str);
+ Ok(path_str)
}
+/// Renames `path` and its SQLite sidecars to `<name>.unusable` (replacing an
+/// earlier one), so a new keychain can take the name.
#[cfg(target_os = "macos")]
-fn target_keychain_path(host: &dyn HostEffects) -> std::path::PathBuf {
- if let Some(p) = std::env::var_os("CUA_ENV_KEYCHAIN") {
- let p = std::path::PathBuf::from(p);
- if !p.as_os_str().is_empty() {
- return p;
+fn set_aside(path: &std::path::Path) {
+ let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
+ return;
+ };
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return;
+ };
+ for entry in entries.flatten() {
+ let file = entry.file_name().to_string_lossy().into_owned();
+ if file.starts_with(name) && !file.ends_with(".unusable") {
+ let _ = std::fs::rename(entry.path(), dir.join(format!("{file}.unusable")));
}
}
- default_keychain_path(host).unwrap_or_else(|| {
- host.home_dir()
- .unwrap_or_default()
- .join("Library/Keychains/login.keychain-db")
- })
}
-/// Path of the user's default keychain — where `security add-generic-password`
-/// puts a new item when no keychain is named. `security default-keychain`
-/// prints it quoted, one line.
+/// Makes spacesd's keychain the first entry of the user's keychain search list,
+/// keeping everything else after it, in order. A no-op when it already is.
#[cfg(target_os = "macos")]
-fn default_keychain_path(host: &dyn HostEffects) -> Option<std::path::PathBuf> {
- let out = host
- .run(
- &HostCommand::new(EffectKind::KeychainRead, "security").args([
- "default-keychain",
- "-d",
- "user",
- ]),
- )
- .ok()?;
- let text = String::from_utf8_lossy(&out.stdout);
- let path = text.trim().trim_matches('"').trim();
- if path.is_empty() {
- None
- } else {
- Some(std::path::PathBuf::from(path))
+fn put_first_on_search_list(host: &dyn HostEffects, path: &str) {
+ let mut list: Vec<String> = Vec::new();
+ if let Ok(o) = security(
+ host,
+ EffectKind::KeychainRead,
+ vec!["list-keychains".into(), "-d".into(), "user".into()],
+ None,
+ ) {
+ for line in String::from_utf8_lossy(&o.stdout).lines() {
+ let p = line.trim().trim_matches('"').to_string();
+ if !p.is_empty() {
+ list.push(p);
+ }
+ }
+ }
+ if list.first().map(String::as_str) == Some(path) {
+ return;
}
+ list.retain(|p| p != path);
+ list.insert(0, path.to_string());
+ let mut args = vec![
+ "list-keychains".to_string(),
+ "-d".into(),
+ "user".into(),
+ "-s".into(),
+ ];
+ args.extend(list);
+ let _ = security(host, EffectKind::KeychainWrite, args, None);
}
-/// Best-effort: make sure the destination's login Keychain won't auto-lock and
-/// re-prompt after we install into it. NON-destructive by design: recreating a
-/// keychain the session already holds open does not give us an unlocked one, it
-/// gives the session a *different*, locked file at the same path, and the first
-/// app to touch it raises "<App> wants to use the '<keychain>' keychain" — an
-/// unanswerable SecurityAgent dialog in an unattended destination. So we only
-/// try a harmless unlock with the account password (which helps for the
-/// keychain the destination created itself, e.g. the Space's `cua` keychain,
-/// and is a no-op for the login keychain, whose password we do not know) and
-/// disable the auto-lock timeout.
-/// Password overridable via `CUA_ENV_LOGIN_KEYCHAIN_PW` (default "lume").
-#[cfg(target_os = "macos")]
-fn ensure_login_unlocked(host: &dyn HostEffects) {
- let Some(home) = host.home_dir() else {
- return;
- };
- let pw = std::env::var("CUA_ENV_LOGIN_KEYCHAIN_PW").unwrap_or_else(|_| "lume".to_string());
- // The login keychain, and the default keychain if it is a different one —
- // the items go into the default, so that is the one that has to be open.
- let mut paths = vec![home.join("Library/Keychains/login.keychain-db")];
- for extra in [
- default_keychain_path(host),
- Some(target_keychain_path(host)),
- ]
- .into_iter()
- .flatten()
+/// Keeps spacesd's keychain open and first on the search list, if it exists:
+/// run at startup and periodically by the server, so a reboot, a wake, a
+/// timeout or something resetting the search list never leaves a LOCKED
+/// keychain for Spotlight and friends to ask about, or lets the login keychain's
+/// own copy of an app's key win the lookup. Never creates the keychain (a Space
+/// that was never teleported into has none). Whether it is open.
+pub fn keep_cua_keychain_unlocked(host: &dyn HostEffects) -> bool {
+ #[cfg(target_os = "macos")]
{
- if !paths.contains(&extra) {
- paths.push(extra);
- }
+ let Some(path) = existing_cua_keychain(host) else {
+ return false;
+ };
+ put_first_on_search_list(host, &path);
+ true
}
- for path in paths {
- let path_str = path.to_string_lossy().into_owned();
- let _ = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security").args([
- "unlock-keychain",
- "-p",
- &pw,
- &path_str,
- ]),
- );
- let _ = host.run(
- &HostCommand::new(EffectKind::KeychainWrite, "security")
- .args(["set-keychain-settings", &path_str]),
- );
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = host;
+ false
}
}
-/// True for the `security -i` call that adds an item (tests).
+/// How often the server re-runs [`keep_cua_keychain_unlocked`].
+pub const KEEPER_INTERVAL: std::time::Duration = std::time::Duration::from_secs(20);
+
#[cfg(test)]
pub(crate) fn is_add_command(call: &crate::host::HostCommand) -> bool {
call.stdin
@@ -975,105 +965,232 @@ mod tests {
/// 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.
+ /// A Space that has never been teleported into, with the login keychain on
+ /// the search list (the shape of a fresh Lume image).
+ #[cfg(target_os = "macos")]
+ fn fresh_space(home: &std::path::Path) -> FakeHost {
+ let login = format!(
+ "\"{}/Library/Keychains/login.keychain-db\"\n",
+ home.display()
+ );
+ FakeHost::new().with_home(home).with_responder(move |c| {
+ Ok(match c.args.first().map(String::as_str) {
+ Some("list-keychains") if !c.args.contains(&"-s".to_string()) => {
+ HostOutput::ok(login.clone())
+ }
+ _ => HostOutput::ok(""),
+ })
+ })
+ }
+
+ /// Every keychain a `security` call names, wherever it appears (argument or
+ /// `security -i` stdin line).
+ #[cfg(target_os = "macos")]
+ fn touched_keychains(call: &crate::host::HostCommand) -> Vec<String> {
+ let mut text: Vec<String> = call.args.clone();
+ if let Some(stdin) = &call.stdin {
+ text.push(String::from_utf8_lossy(stdin.as_bytes()).into_owned());
+ }
+ text.iter()
+ .flat_map(|t| t.split('"').map(str::to_string).collect::<Vec<_>>())
+ .filter(|t| t.ends_with(".keychain-db") || t.ends_with(".keychain"))
+ .collect()
+ }
+
#[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(""),
- })
- });
+ fn chrome_s_key_goes_into_spacesds_keychain_first_on_the_search_list() {
+ let home = tempfile::tempdir().unwrap();
+ let host = fresh_space(home.path());
let mut notes = Vec::new();
install_generic_noted(&host, &chrome_item(), &mut notes).unwrap();
assert!(notes.is_empty(), "{notes:?}");
+ let cua = format!(
+ "{}/Library/Keychains/cua.keychain-db",
+ home.path().display()
+ );
+ let login = format!(
+ "{}/Library/Keychains/login.keychain-db",
+ home.path().display()
+ );
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:?}"
+ // Created with a password spacesd knows, kept open, never auto-locked.
+ assert!(writes.iter().any(
+ |c| c.args == ["create-keychain", "-p", "lume", cua.as_str()]
+ || c.args.first().map(String::as_str) == Some("create-keychain")
+ && c.args.last().map(String::as_str) == Some(cua.as_str())
+ ));
+ assert!(writes
+ .iter()
+ .any(|c| c.args == ["set-keychain-settings", cua.as_str()]));
+ // FIRST on the list, the login keychain after it (the app's lookup takes
+ // the first match, so ours wins over the key the app made itself).
+ let set_list = writes
+ .iter()
+ .find(|c| c.args.first().map(String::as_str) == Some("list-keychains"))
+ .expect("the search list was written");
+ assert_eq!(set_list.args[4..], [cua.clone(), login.clone()]);
+ // The item and its authorization are in OUR keychain.
+ assert_eq!(writes.iter().filter(|c| is_add_command(c)).count(), 1);
+ let add = writes.iter().find(|c| is_add_command(c)).unwrap();
+ assert!(touched_keychains(add).iter().all(|k| *k == cua), "{add:?}");
+ let last = partition_calls(&host).pop().unwrap();
+ assert_eq!(last.args.last().map(String::as_str), Some(cua.as_str()));
+ assert!(last.args[2].contains("teamid:EQHXZ8M8AV"));
+ }
+
+ /// The prompt this fix exists for: `security` reading, deleting or
+ /// re-authorizing an item in the login keychain (Chrome's own Safe Storage
+ /// item trusts only Chrome; the login keychain's password is not the
+ /// account password). Whatever happens, no call may name it other than to
+ /// list the search list.
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn spacesd_never_touches_the_login_keychain() {
+ let home = tempfile::tempdir().unwrap();
+ let login = format!(
+ "{}/Library/Keychains/login.keychain-db",
+ home.path().display()
);
- // On the search list, but never made the default (system services
- // would reach for it and prompt whenever it is locked).
+ for existing_cua_keychain in [false, true] {
+ if existing_cua_keychain {
+ let dir = home.path().join("Library/Keychains");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("cua.keychain-db"), b"").unwrap();
+ }
+ let host = fresh_space(home.path());
+ let mut record = ImportRecord::default();
+ let items = cua_teleport_bundle::keychain::serialize(&[chrome_item()]);
+ assert_eq!(install_all_recorded(&host, &items, &mut record), 1);
+ let _ = read_secret(&host, "Chrome Safe Storage", "Chrome");
+ let _ = keep_cua_keychain_unlocked(&host);
+ let _ = remove_generic(&host, "Chrome Safe Storage", "Chrome");
+ for call in host.calls() {
+ let list_only = call.args.first().map(String::as_str) == Some("list-keychains");
+ let names_login = touched_keychains(&call).contains(&login);
+ assert!(
+ !names_login || list_only,
+ "a call touched the login keychain: {call:?}"
+ );
+ if call.program == "security" {
+ assert!(
+ call.timeout.is_some(),
+ "an unbounded security call: {call:?}"
+ );
+ }
+ }
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn a_security_call_stuck_on_a_dialog_fails_fast_and_dismisses_it() {
+ let home = tempfile::tempdir().unwrap();
+ let host = FakeHost::new().with_home(home.path()).with_responder(|c| {
+ if c.args.first().map(String::as_str) == Some("create-keychain") {
+ Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "hung"))
+ } else {
+ Ok(HostOutput::ok(""))
+ }
+ });
+ let started = std::time::Instant::now();
+ let err = install_generic_noted(&host, &chrome_item(), &mut Vec::new()).unwrap_err();
+ assert!(started.elapsed() < std::time::Duration::from_secs(5));
+ assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
assert!(
- writes
- .iter()
- .all(|c| c.args.first().map(String::as_str) != Some("default-keychain")),
- "{writes:?}"
+ err.to_string().contains("waiting on a Keychain dialog"),
+ "{err}"
);
+ let kills = host.calls_of(EffectKind::ProcessTerminate);
assert!(
- writes.iter().any(
- |c| c.args.first().map(String::as_str) == Some("list-keychains")
- && c.args.last().map(String::as_str) == Some(known)
- ),
- "{writes:?}"
+ kills
+ .iter()
+ .any(|c| c.args == ["-KILL", "-x", "SecurityAgent"]),
+ "the dialog is dismissed: {kills:?}"
);
- // Open, with no lock-on-sleep and no timeout (no -l, -u or -t).
- assert!(
- writes.iter().any(|c| c.args.first().map(String::as_str)
- == Some("set-keychain-settings")
- && c.args == ["set-keychain-settings", known]),
- "{writes:?}"
+ assert!(host
+ .calls()
+ .iter()
+ .filter(|c| c.program == "security")
+ .all(|c| c.timeout == Some(SECURITY_TIMEOUT)));
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn a_keychain_that_takes_no_known_password_is_set_aside_and_replaced() {
+ let home = tempfile::tempdir().unwrap();
+ let dir = home.path().join("Library/Keychains");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("cua.keychain-db"), b"old").unwrap();
+ let created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let seen = created.clone();
+ let host = FakeHost::new()
+ .with_home(home.path())
+ .with_responder(move |c| {
+ let sub = c.args.first().map(String::as_str);
+ if sub == Some("create-keychain") {
+ seen.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ // Until it is recreated, no password opens it.
+ Ok(
+ if sub == Some("unlock-keychain")
+ && !seen.load(std::sync::atomic::Ordering::SeqCst)
+ {
+ HostOutput::failed()
+ } else {
+ HostOutput::ok("")
+ },
+ )
+ });
+ install_generic_noted(&host, &chrome_item(), &mut Vec::new()).unwrap();
+ assert!(created.load(std::sync::atomic::Ordering::SeqCst));
+ assert_eq!(
+ std::fs::read(dir.join("cua.keychain-db.unusable")).unwrap(),
+ b"old",
+ "set aside, never deleted"
);
- // 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"));
}
- /// The `cua` keychain is reopened (and told never to lock) by the
- /// keeper, with the first password that takes; a Space whose login
- /// keychain took the password has no `cua` keychain and nothing happens.
#[cfg(target_os = "macos")]
#[test]
fn the_keeper_unlocks_the_cua_keychain_and_never_auto_locks_it() {
- let dir = std::env::temp_dir().join(format!("cua-keeper-{}", std::process::id()));
- let kc = dir.join("Library/Keychains");
+ let dir = tempfile::tempdir().unwrap();
+ let kc = dir.path().join("Library/Keychains");
std::fs::create_dir_all(&kc).unwrap();
let path = kc.join("cua.keychain-db");
- let none = FakeHost::new().with_home(&dir);
+ let p = path.to_string_lossy().into_owned();
+ let none = FakeHost::new().with_home(dir.path());
assert!(!keep_cua_keychain_unlocked(&none), "no keychain, no work");
assert!(none.calls().is_empty());
std::fs::write(&path, b"").unwrap();
- // The first password (an env one nobody set) is skipped: only `lume` opens it.
- let host = FakeHost::new().with_home(&dir).with_responder(|c| {
- Ok(
- if c.args.first().map(String::as_str) == Some("unlock-keychain")
- && c.args[2] != "lume"
- {
- HostOutput::failed()
- } else {
- HostOutput::ok("")
- },
- )
- });
+ let login = format!(
+ "\"{}/Library/Keychains/login.keychain-db\"\n",
+ dir.path().display()
+ );
+ let host = FakeHost::new()
+ .with_home(dir.path())
+ .with_responder(move |c| {
+ Ok(match c.args.first().map(String::as_str) {
+ Some("unlock-keychain") if c.args[2] != "lume" => HostOutput::failed(),
+ // The search list lost our keychain (something reset it).
+ Some("list-keychains") if !c.args.contains(&"-s".to_string()) => {
+ HostOutput::ok(login.clone())
+ }
+ _ => HostOutput::ok(""),
+ })
+ });
assert!(keep_cua_keychain_unlocked(&host));
let calls = host.calls_of(EffectKind::KeychainWrite);
- let p = path.to_string_lossy().into_owned();
- assert_eq!(
- calls.last().unwrap().args,
- ["set-keychain-settings".to_string(), p.clone()],
- "no -l / -u / -t: no lock on sleep, no timeout"
+ assert!(calls
+ .iter()
+ .any(|c| c.args == ["set-keychain-settings".to_string(), p.clone()]));
+ assert!(
+ calls.iter().all(|c| !c
+ .args
+ .iter()
+ .any(|a| matches!(a.as_str(), "-l" | "-u" | "-t"))),
+ "no lock on sleep, no timeout"
);
assert!(calls.iter().any(|c| c.args
== [
@@ -1082,40 +1199,58 @@ mod tests {
"lume".into(),
p.clone()
]));
+ let relist = calls
+ .iter()
+ .find(|c| c.args.first().map(String::as_str) == Some("list-keychains"))
+ .expect("our keychain is put back at the front");
+ assert_eq!(relist.args[4], p);
+
+ // Already first: the search list is left alone.
+ let host = FakeHost::new().with_home(dir.path()).with_responder({
+ let p = p.clone();
+ move |c| {
+ Ok(match c.args.first().map(String::as_str) {
+ Some("list-keychains") if !c.args.contains(&"-s".to_string()) => {
+ HostOutput::ok(format!("\"{p}\"\n"))
+ }
+ _ => HostOutput::ok(""),
+ })
+ }
+ });
+ assert!(keep_cua_keychain_unlocked(&host));
+ assert!(host.calls_of(EffectKind::KeychainWrite).iter().all(|c| c
+ .args
+ .first()
+ .map(String::as_str)
+ != Some("list-keychains")));
- // A password that never takes: still tries, reports closed, sets nothing.
let host = FakeHost::new()
- .with_home(&dir)
+ .with_home(dir.path())
.with_responder(|_| Ok(HostOutput::failed()));
assert!(!keep_cua_keychain_unlocked(&host));
assert!(host
.calls()
.iter()
.all(|c| c.args.first().map(String::as_str) != Some("set-keychain-settings")));
- let _ = std::fs::remove_dir_all(&dir);
}
- /// When no password works anywhere, the teleport says so in words the
- /// user can act on.
+ /// If the app cannot be pre-authorized (it would prompt), the teleport
+ /// fails, fast and clearly, instead of leaving it to hang on a dialog.
#[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:?}");
+ fn an_item_that_cannot_be_authorized_stops_the_teleport() {
+ let home = tempfile::tempdir().unwrap();
+ let host = FakeHost::new().with_home(home.path()).with_responder(|c| {
+ Ok(match c.args.first().map(String::as_str) {
+ Some("set-generic-password-partition-list") => HostOutput::failed(),
+ _ => HostOutput::ok(""),
+ })
+ });
+ let err = install_generic_noted(&host, &chrome_item(), &mut Vec::new()).unwrap_err();
assert!(
- notes[0].starts_with("Chrome will ask once for the Space's login password"),
- "{notes:?}"
+ err.to_string()
+ .contains("could not pre-authorize Chrome to read its saved key"),
+ "{err}"
);
}
@@ -1132,22 +1267,30 @@ mod tests {
#[cfg(target_os = "macos")]
#[test]
- fn remove_goes_through_the_injected_host() {
+ fn remove_goes_through_the_injected_host_and_only_in_spacesds_keychain() {
+ let home = tempfile::tempdir().unwrap();
+ let kc = home.path().join("Library/Keychains");
+ std::fs::create_dir_all(&kc).unwrap();
+ std::fs::write(kc.join("cua.keychain-db"), b"").unwrap();
let host = FakeHost::new()
- .with_home("/nonexistent-fake-home")
- .with_responder(|c| {
- Ok(
- if c.args.first().map(String::as_str) == Some("delete-generic-password") {
- HostOutput::ok("")
- } else {
- HostOutput::failed()
- },
- )
- });
+ .with_home(home.path())
+ .with_responder(|_| Ok(HostOutput::ok("")));
assert!(remove_generic(&host, "svc", "acct").unwrap());
- let deletes = host.calls_of(EffectKind::KeychainWrite);
- assert!(!deletes.is_empty());
- assert!(deletes.iter().all(|c| c.program == "security"
- && c.args[..5] == ["delete-generic-password", "-s", "svc", "-a", "acct"]));
+ let deletes: Vec<_> = host
+ .calls_of(EffectKind::KeychainWrite)
+ .into_iter()
+ .filter(|c| c.args.first().map(String::as_str) == Some("delete-generic-password"))
+ .collect();
+ assert_eq!(deletes.len(), 1, "{deletes:?}");
+ assert_eq!(deletes[0].program, "security");
+ assert_eq!(
+ deletes[0].args[..5],
+ ["delete-generic-password", "-s", "svc", "-a", "acct"]
+ );
+ assert!(deletes[0].args[5].ends_with("cua.keychain-db"));
+ // No keychain of ours yet: nothing to remove, nothing run.
+ let none = FakeHost::new().with_home("/nonexistent-fake-home");
+ assert!(!remove_generic(&none, "svc", "acct").unwrap());
+ assert!(none.calls().is_empty());
}
}
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 62c2a13dbf..54397721df 100644
--- a/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
+++ b/libs/cua-spacesd/crates/cua-spacesd-teleport/tests/import.rs
@@ -17,8 +17,16 @@ use cua_spacesd_teleport::host::HostOutput;
use cua_spacesd_teleport::{EffectKind, FakeHost, ImportError, Receiver, TransferScope};
fn fake_receiver(dest: &Path) -> (Arc<FakeHost>, Receiver) {
- // Every host command "succeeds" (`open` returns 0), nothing real runs.
- let host = Arc::new(FakeHost::new().with_responder(|_| Ok(HostOutput::ok("501"))));
+ // Every host command "succeeds" (`open` returns 0), nothing real runs, and
+ // no browser is running (a `pgrep` that matched would make the import wait
+ // for it to quit).
+ let host = Arc::new(FakeHost::new().with_responder(|c| {
+ Ok(if c.kind == EffectKind::ProcessLookup {
+ HostOutput::failed()
+ } else {
+ HostOutput::ok("501")
+ })
+ }));
let receiver = Receiver::with_host(dest.to_path_buf(), host.clone());
(host, receiver)
}
@@ -109,6 +117,8 @@ fn a_failed_launch_is_reported_and_the_import_still_succeeds() {
stdout: vec![],
stderr: b"The application cannot be opened".to_vec(),
}
+ } else if c.kind == EffectKind::ProcessLookup {
+ HostOutput::failed()
} else {
HostOutput::ok("501")
})
@@ -128,7 +138,15 @@ fn import_without_launch_records_nothing() {
let (host, receiver) = fake_receiver(dest.path());
let outcome = receiver.import_bytes(&chrome_bundle(), "", false).unwrap();
assert!(!outcome.launched);
- assert!(host.calls().is_empty(), "{:?}", host.calls());
+ // Only the look for a running Chrome (to quit before its profile is
+ // replaced): nothing is launched, killed, or written to the Keychain.
+ assert!(
+ host.calls()
+ .iter()
+ .all(|c| c.kind == EffectKind::ProcessLookup),
+ "{:?}",
+ host.calls()
+ );
}
#[test]
diff --git a/libs/cua-spacesd/tests/teleport-e2e/examples/send_synthetic_chrome.rs b/libs/cua-spacesd/tests/teleport-e2e/examples/send_synthetic_chrome.rs
new file mode 100644
index 0000000000..28dce26b9a
--- /dev/null
+++ b/libs/cua-spacesd/tests/teleport-e2e/examples/send_synthetic_chrome.rs
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Teleport a SYNTHETIC Chrome profile into a real, running cua-spacesd (a Lume
+//! Space), the way the Cua Spaces app does, for the guest-side manual/E2E
+//! proof of `fix(teleport): Chrome Safe Storage without keychain prompts`.
+//!
+//! Never reads the host's Chrome, profile or keychain: the source is a
+//! throwaway directory holding a fake Chrome profile whose cookie store has
+//! one plaintext test cookie. The receiver (in the Space) re-encrypts it under
+//! the Space's own Safe Storage key, exactly as it does for a Keyvault or live
+//! teleport (all three deliver the same bundle to the same receiver).
+//!
+//! ```text
+//! cargo run --example send_synthetic_chrome -- http://192.168.64.206:3211 <token> [host] [name] [value]
+//! ```
+
+use std::sync::Arc;
+
+use cua_spacesd_client::{ConnectOptions, SpacesdClient, TransportPreference};
+use cua_teleport::providers::chrome::ChromeProvider;
+use cua_teleport::{
+ AppRef, ExportRegistry, Platform, Selection, SendOptions, Teleporter, TransferScope,
+};
+
+#[tokio::main(flavor = "multi_thread", worker_threads = 2)]
+async fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let (url, token) = match (args.first(), args.get(1)) {
+ (Some(u), Some(t)) => (u.clone(), t.clone()),
+ _ => {
+ eprintln!("usage: send_synthetic_chrome <spacesd-url> <token> [host] [name] [value]");
+ std::process::exit(2);
+ }
+ };
+ let host_key = args.get(2).cloned().unwrap_or_else(|| "localhost".into());
+ let name = args.get(3).cloned().unwrap_or_else(|| "cua_session".into());
+ let value = args
+ .get(4)
+ .cloned()
+ .unwrap_or_else(|| "alice-signed-in".into());
+
+ let src = tempfile::tempdir().unwrap();
+ let profile = src.path().join(".config/google-chrome/Default");
+ std::fs::create_dir_all(profile.join("Network")).unwrap();
+ let conn = rusqlite::Connection::open(profile.join("Network/Cookies")).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE 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, 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,
+ UNIQUE (host_key, top_frame_site_key, name, path));",
+ )
+ .unwrap();
+ conn.execute(
+ "INSERT INTO cookies (creation_utc, host_key, name, value, path, expires_utc, is_secure, is_httponly)
+ VALUES (13300000000000000, ?1, ?2, ?3, '/', 13600000000000000, 0, 0)",
+ rusqlite::params![host_key, name, value],
+ )
+ .unwrap();
+ drop(conn);
+ std::fs::write(profile.join("Preferences"), b"{}").unwrap();
+
+ let sender_host = Arc::new(cua_teleport::FakeHost::new().with_home(src.path()));
+ let mut registry = ExportRegistry::new();
+ registry.register(Box::new(
+ ChromeProvider::new()
+ .without_devtools()
+ .with_host(sender_host),
+ ));
+ let teleporter = Teleporter::with_registry(registry).options(SendOptions::default());
+
+ let transport = if std::env::var_os("GRPC_WEB").is_some() {
+ TransportPreference::GrpcWeb
+ } else {
+ TransportPreference::Native
+ };
+ let env = SpacesdClient::connect(
+ ConnectOptions::parse(&url)
+ .unwrap()
+ .token(token)
+ .transport(transport),
+ )
+ .await
+ .expect("connect to the Space's cua-spacesd");
+ let chrome = AppRef {
+ app_id: "google-chrome".into(),
+ display_name: "Google Chrome".into(),
+ platform: Platform::Linux,
+ };
+ let started = std::time::Instant::now();
+ match teleporter
+ .send(
+ &env,
+ &chrome,
+ TransferScope::FullProfile,
+ Selection::All,
+ Arc::new(|_: &cua_teleport::ApprovalRequest<'_>| true),
+ )
+ .await
+ {
+ Ok(outcome) => println!("TELEPORT OK in {:?}: {outcome:?}", started.elapsed()),
+ Err(e) => {
+ println!("TELEPORT FAILED after {:?}: {e}", started.elapsed());
+ std::process::exit(1);
+ }
+ }
+}