Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-auth): keep the sign-in under ai.cua.session and move it from run.cua.ai (CUA-1877) (#5436)
Francesco Bonacci7eb732acd364
diff --git a/docs/content/docs/cua-cli/guides/authentication.mdx b/docs/content/docs/cua-cli/guides/authentication.mdxindex b6ab92f427..42c10ebc41 100644--- a/docs/content/docs/cua-cli/guides/authentication.mdx+++ b/docs/content/docs/cua-cli/guides/authentication.mdx@@ -26,7 +26,7 @@ printed.| Platform | Session stored in ||----------|-------------------|-| macOS, builds signed by Cua | Keychain, service `run.cua.ai`, account `cua-cli` |+| macOS, builds signed by Cua | Keychain, service `ai.cua.session`, account `cua-cli` || macOS, builds from source | `~/.cua/credentials.json`, mode 600 || Windows | Credential Manager, same service and account || Linux | `~/.cua/credentials.json`, mode 600 |@@ -35,6 +35,16 @@ printed.is a new app to the Keychain every time it is rebuilt, so it uses the file andnever asks for Keychain access.+Older versions kept the session, the device key and the other secrets under the+service `run.cua.ai` (`staging.run.cua.ai` for staging). The first `cua` that+reads them after you update moves each item to `ai.cua.session`, checks the new+item and then deletes the old one, so you stay signed in. A `cua` signed by Cua+does this without a password prompt, and so does every later update of it.+If macOS would have to ask (the item was created by a program the update does+not trust), `cua` leaves the old item as it is. Run `cua auth keychain --prompt`+in a terminal once and choose Always Allow, or sign in again.+`cua auth logout` removes both the new and the old items.+On macOS, `cua` never waits on a Keychain dialog it cannot show. Run from aterminal it lets macOS ask for access. Run without one (by an agent, a scriptor a service) it fails within seconds with a message instead of hanging, also@@ -70,7 +80,7 @@ cua auth status # starts with "Environment: staging (...)"| Spaces API | `CUA_SPACES_API_URL` | `https://api.cua.ai` || Spaces site (add-machine links `<site>/add/<code>`) | `CUA_SPACES_SITE_URL` | `https://spaces.cua.ai` || cua home | `CUA_HOME` | `~/.cua` (`~/.cua/envs/staging` for staging) |-| Keychain / Credential Manager service | none | `run.cua.ai` (`staging.run.cua.ai` for staging) |+| Keychain / Credential Manager service | none | `ai.cua.session` (`ai.cua.session.staging` for staging) |Each environment has its own session, host enrollment, Spaces registry anddaemon, so signing in to staging never replaces or sends your productiondiff --git a/libs/cua/crates/cua-auth/src/legacy_vault.rs b/libs/cua/crates/cua-auth/src/legacy_vault.rsnew file mode 100644index 0000000000..d13407b314--- /dev/null+++ b/libs/cua/crates/cua-auth/src/legacy_vault.rs@@ -0,0 +1,283 @@+//! Moving a vault item from the legacy service name to the current one.+//!+//! Builds before CUA-1877 kept the session, the device key and the other+//! named secrets under a service named after the retired Cloud API host+//! (`run.cua.ai`, `staging.run.cua.ai`). The current builds use `ai.cua.session`+//! (`ai.cua.session.staging`); the account names stay as they were+//! (`cua-cli`, `cua-cli.<name>`). The first read that finds the current item+//! missing moves the legacy one over, so nobody has to sign in again.+//!+//! The move never loses a secret and never leaves two live copies behind:+//!+//! 1. read the legacy item (a read that needs a prompt this process may not+//! show fails here, and nothing has changed);+//! 2. write the current item (a failed write leaves the legacy item as it+//! was);+//! 3. read the current item back and compare (a copy that cannot be read+//! back is deleted again, and the legacy item stays);+//! 4. only then delete the legacy item. If that fails the current item+//! wins from now on and the legacy one is ignored.+//!+//! So a crash, a refusal or a locked keychain at any step leaves the user+//! with at least the session they had, and running the move again is safe: a+//! missing legacy item is "nothing to do", and the callers only start a move+//! while the current item is missing.+//!+//! The logic is generic over a [`Vault`] so it is tested on every platform;+//! macOS plugs in the keychain, Windows the Credential Manager.+//!+//! **Lifetime.** This code and `CuaEnv::legacy_keyring_service` are for the+//! releases around the rename. Remove them two releases or 60 days after the+//! first release that carries the move, whichever is later.++/// A vault that holds text items per `(service, account)`.+pub(crate) trait Vault {+ type Err;+ /// The item, or `None` when there is none.+ fn read(&self, service: &str, account: &str) -> Result<Option<String>, Self::Err>;+ /// Creates or replaces the item.+ fn write(&self, service: &str, account: &str, text: &str) -> Result<(), Self::Err>;+ /// Deletes the item; a missing one is not an error.+ fn delete(&self, service: &str, account: &str) -> Result<(), Self::Err>;+}++/// Why a move did not complete. The legacy item is intact in every case.+#[derive(Debug, PartialEq, Eq)]+pub(crate) enum Failure<E> {+ /// The legacy item could not be read (typically: it needs a prompt).+ Read(E),+ /// The current item could not be written.+ Write(E),+ /// The current item was written but did not read back the same, so it+ /// was deleted again.+ Unverified,+}++/// Moves `account` from `legacy` to `current`. `Ok(None)`: there is no legacy+/// item. `Ok(Some(text))`: the item is now under `current` (and, unless its+/// deletion was refused, gone from `legacy`).+///+/// The caller has checked that `current` has no item for `account`: this+/// never overwrites one.+pub(crate) fn move_item<V: Vault>(+ vault: &V,+ legacy: &str,+ current: &str,+ account: &str,+) -> Result<Option<String>, Failure<V::Err>> {+ let Some(text) = vault.read(legacy, account).map_err(Failure::Read)? else {+ return Ok(None);+ };+ vault+ .write(current, account, &text)+ .map_err(Failure::Write)?;+ if !matches!(vault.read(current, account), Ok(Some(back)) if back == text) {+ let _ = vault.delete(current, account);+ return Err(Failure::Unverified);+ }+ // Best effort: a legacy item that cannot be deleted (not ours to delete,+ // or a prompt this process may not show) is simply not used any more.+ let _ = vault.delete(legacy, account);+ Ok(Some(text))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::RefCell;+ use std::collections::BTreeMap;++ const LEGACY: &str = "run.cua.ai";+ const CURRENT: &str = "ai.cua.session";++ /// An in-memory vault whose operations can be made to fail.+ #[derive(Default)]+ struct Fake {+ items: RefCell<BTreeMap<(String, String), String>>,+ fail_read: RefCell<Vec<(String, String)>>,+ fail_write: RefCell<bool>,+ fail_delete: RefCell<Vec<(String, String)>>,+ /// Writes to `CURRENT` store this instead of the text.+ garble_write: RefCell<bool>,+ log: RefCell<Vec<String>>,+ }++ impl Fake {+ fn with(items: &[(&str, &str, &str)]) -> Self {+ let f = Self::default();+ for (s, a, t) in items {+ f.items+ .borrow_mut()+ .insert((s.to_string(), a.to_string()), t.to_string());+ }+ f+ }+ fn get(&self, s: &str, a: &str) -> Option<String> {+ self.items+ .borrow()+ .get(&(s.to_string(), a.to_string()))+ .cloned()+ }+ fn log(&self) -> Vec<String> {+ self.log.borrow().clone()+ }+ }++ impl Vault for Fake {+ type Err = String;+ fn read(&self, s: &str, a: &str) -> Result<Option<String>, String> {+ self.log.borrow_mut().push(format!("read {s} {a}"));+ if self.fail_read.borrow().contains(&(s.into(), a.into())) {+ return Err("needs a prompt".into());+ }+ Ok(self.get(s, a))+ }+ fn write(&self, s: &str, a: &str, t: &str) -> Result<(), String> {+ self.log.borrow_mut().push(format!("write {s} {a}"));+ if *self.fail_write.borrow() {+ return Err("write refused".into());+ }+ let stored = if *self.garble_write.borrow() {+ format!("{t}?")+ } else {+ t.to_string()+ };+ self.items+ .borrow_mut()+ .insert((s.to_string(), a.to_string()), stored);+ Ok(())+ }+ fn delete(&self, s: &str, a: &str) -> Result<(), String> {+ self.log.borrow_mut().push(format!("delete {s} {a}"));+ if self.fail_delete.borrow().contains(&(s.into(), a.into())) {+ return Err("delete refused".into());+ }+ self.items+ .borrow_mut()+ .remove(&(s.to_string(), a.to_string()));+ Ok(())+ }+ }++ fn run(f: &Fake, account: &str) -> Result<Option<String>, Failure<String>> {+ move_item(f, LEGACY, CURRENT, account)+ }++ #[test]+ fn a_legacy_item_moves_and_the_old_one_is_deleted() {+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ assert_eq!(run(&f, "cua-cli"), Ok(Some("session".into())));+ assert_eq!(f.get(CURRENT, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(LEGACY, "cua-cli"), None);+ // The new item is written and verified before the old one goes.+ assert_eq!(+ f.log(),+ [+ format!("read {LEGACY} cua-cli"),+ format!("write {CURRENT} cua-cli"),+ format!("read {CURRENT} cua-cli"),+ format!("delete {LEGACY} cua-cli"),+ ]+ );+ }++ #[test]+ fn without_a_legacy_item_nothing_happens() {+ let f = Fake::default();+ assert_eq!(run(&f, "cua-cli"), Ok(None));+ assert_eq!(f.get(CURRENT, "cua-cli"), None);+ assert_eq!(f.log(), [format!("read {LEGACY} cua-cli")]);+ }++ #[test]+ fn a_failed_read_leaves_the_old_item_intact_and_creates_nothing() {+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ f.fail_read+ .borrow_mut()+ .push((LEGACY.into(), "cua-cli".into()));+ assert_eq!(+ run(&f, "cua-cli"),+ Err(Failure::Read("needs a prompt".into()))+ );+ assert_eq!(f.get(LEGACY, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(CURRENT, "cua-cli"), None);+ // It never wrote or deleted anything.+ assert_eq!(f.log(), [format!("read {LEGACY} cua-cli")]);+ }++ #[test]+ fn a_failed_write_leaves_the_old_item_intact() {+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ *f.fail_write.borrow_mut() = true;+ assert_eq!(+ run(&f, "cua-cli"),+ Err(Failure::Write("write refused".into()))+ );+ assert_eq!(f.get(LEGACY, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(CURRENT, "cua-cli"), None);+ }++ #[test]+ fn a_copy_that_does_not_read_back_is_dropped_and_the_old_item_stays() {+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ *f.garble_write.borrow_mut() = true;+ assert_eq!(run(&f, "cua-cli"), Err(Failure::Unverified));+ assert_eq!(f.get(LEGACY, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(CURRENT, "cua-cli"), None);+ // A copy that cannot be read at all is the same.+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ f.fail_read+ .borrow_mut()+ .push((CURRENT.into(), "cua-cli".into()));+ assert_eq!(run(&f, "cua-cli"), Err(Failure::Unverified));+ assert_eq!(f.get(LEGACY, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(CURRENT, "cua-cli"), None);+ }++ #[test]+ fn a_refused_delete_keeps_the_move() {+ let f = Fake::with(&[(LEGACY, "cua-cli", "session")]);+ f.fail_delete+ .borrow_mut()+ .push((LEGACY.into(), "cua-cli".into()));+ assert_eq!(run(&f, "cua-cli"), Ok(Some("session".into())));+ assert_eq!(f.get(CURRENT, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(LEGACY, "cua-cli").as_deref(), Some("session"));+ }++ #[test]+ fn running_it_again_is_a_no_op() {+ let f = Fake::with(&[+ (LEGACY, "cua-cli", "session"),+ (LEGACY, "cua-cli.device-key", "key"),+ ]);+ for account in ["cua-cli", "cua-cli.device-key"] {+ assert!(run(&f, account).unwrap().is_some());+ }+ let after = f.items.borrow().clone();+ // The legacy items are gone, so a second run finds nothing to move+ // and changes nothing.+ for account in ["cua-cli", "cua-cli.device-key"] {+ assert_eq!(run(&f, account), Ok(None));+ }+ assert_eq!(*f.items.borrow(), after);+ assert_eq!(f.get(CURRENT, "cua-cli.device-key").as_deref(), Some("key"));+ }++ #[test]+ fn each_account_moves_on_its_own() {+ let f = Fake::with(&[+ (LEGACY, "cua-cli", "session"),+ (LEGACY, "cua-cli.device-key", "key"),+ ]);+ // The device key needs a prompt; the session does not.+ f.fail_read+ .borrow_mut()+ .push((LEGACY.into(), "cua-cli.device-key".into()));+ assert!(run(&f, "cua-cli").is_ok());+ assert!(run(&f, "cua-cli.device-key").is_err());+ assert_eq!(f.get(CURRENT, "cua-cli").as_deref(), Some("session"));+ assert_eq!(f.get(CURRENT, "cua-cli.device-key"), None);+ assert_eq!(f.get(LEGACY, "cua-cli.device-key").as_deref(), Some("key"));+ }+}diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rsindex b61cc922fc..e3e099881d 100644--- a/libs/cua/crates/cua-auth/src/lib.rs+++ b/libs/cua/crates/cua-auth/src/lib.rs@@ -7,7 +7,7 @@//! for the client and falls back to the device flow when it does not, so//! it works before and after that client change lands.//! - **Store**: the OS credential vault on Windows and on macOS for builds-//! signed by Cua (service `run.cua.ai`, `staging.run.cua.ai` for+//! signed by Cua (service `ai.cua.session`, `ai.cua.session.staging` for//! `CUA_ENV=staging`; account `cua-cli`), a 0600//! `~/.cua/credentials.json` elsewhere (Linux, and unsigned or ad-hoc//! macOS builds, which macOS treats as a new app on every rebuild so@@ -21,6 +21,9 @@//! none (never writing it back to a file).//! A process without a terminal (an agent, a script, a service) never//! waits on a macOS keychain prompt: see [`KEYCHAIN_NONINTERACTIVE_ENV`].+//! Items that older builds stored under the service `run.cua.ai`+//! (`staging.run.cua.ai`) move to the current service on first read, and+//! sign-out removes both: see `legacy_vault`.//! - **Session**: a refreshing access token. Every call reads the store, so//! a sign-out or a token another process rotated is seen at once instead//! of being refreshed twice.@@ -49,12 +52,18 @@ const DEFAULT_SCOPE: &str = "openid profile offline_access organization:*";const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";/// Refresh this long before expiry.const REFRESH_SKEW_SECS: i64 = 60;-/// The OS vault service of the session: `run.cua.ai` in production,+/// The OS vault service of the session: `ai.cua.session` in production,/// another one per `CUA_ENV`, so environments never share a session.#[cfg(any(target_os = "macos", target_os = "windows"))]fn keyring_service() -> &'static str {cua_home::env::CuaEnv::current().keyring_service()}+/// The service older builds used (`run.cua.ai`, `staging.run.cua.ai`): read+/// once to move its items to [`keyring_service`], and cleared on sign-out.+#[cfg(any(target_os = "macos", target_os = "windows"))]+fn legacy_keyring_service() -> &'static str {+ cua_home::env::CuaEnv::current().legacy_keyring_service()+}#[cfg(any(target_os = "macos", target_os = "windows"))]const KEYRING_ACCOUNT: &str = "cua-cli";/// The Spaces app's former session file under `~/.cua`.@@ -93,6 +102,8 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;mod callback_page;#[allow(dead_code)]mod chunked;+#[allow(dead_code)]+mod legacy_vault;#[cfg(target_os = "macos")]mod macos_keychain;@@ -471,11 +482,17 @@ impl Store {match self {#[cfg(target_os = "macos")]Store::Keyring => {- let wanted = |a: &str| {- a == KEYRING_ACCOUNT- || a.strip_prefix(KEYRING_ACCOUNT)- .is_some_and(|r| r.starts_with('.'))- };+ let wanted = is_cua_account;+ // Items still under the legacy service name move first (a+ // read that needs a prompt is not asked unless `prompt`).+ let moved = macos_keychain::migrate_legacy(+ macos_keychain::Keychain::Default,+ legacy_keyring_service(),+ keyring_service(),+ &wanted,+ prompt,+ signed_by_cua(),+ );let items = macos_keychain::check_items(macos_keychain::Keychain::Default,keyring_service(),@@ -483,6 +500,7 @@ impl Store {prompt,signed_by_cua(),);+ let items = merge_moved(items, moved);KeychainCheck::from_items(items, || {macos_keychain::default_keychain_unlocked() == Some(false)})@@ -497,15 +515,29 @@ impl Store {/// Starts over when the keychain cannot be read ("Sign in again"):/// removes the stored session without reading it, and every other Cua/// item this process cannot read without a prompt (a secret this build- /// can never use without one). Then checks again, without a prompt.+ /// can never use without one), under the current service name and under+ /// the legacy one. Then checks again, without a prompt.pub fn forget_keychain(&self) -> Result<KeychainCheck> {self.clear()?;#[cfg(target_os = "macos")]- for item in &self.check_keychain(false).items {- if matches!(item.state, KeychainState::NeedsAccess)- && let Ok(entry) = keyring::Entry::new(keyring_service(), &item.account)- {- let _ = vault_delete(entry);+ if matches!(self, Store::Keyring) {+ for service in [keyring_service(), legacy_keyring_service()] {+ // Not `check_keychain`: that would move a readable legacy+ // item over, and this is a sign-out.+ let items = macos_keychain::check_items(+ macos_keychain::Keychain::Default,+ service,+ &is_cua_account,+ false,+ false,+ );+ for (account, state) in items {+ if state == macos_keychain::ItemState::NeedsAccess+ && let Ok(entry) = keyring::Entry::new(service, &account)+ {+ let _ = vault_delete(entry);+ }+ }}}Ok(self.check_keychain(false))@@ -624,7 +656,9 @@ impl Store {) {return self.load_stored();}- None+ // Not under the current service name: an older build may+ // have stored it under the legacy one.+ move_legacy_item(KEYRING_ACCOUNT)?}Err(e) => return Err(vault_err(e)),},@@ -681,11 +715,15 @@ impl Store {Err(e) => Err(store_err(e)),},#[cfg(any(target_os = "macos", target_os = "windows"))]- Store::Keyring => match vault_delete(keyring_entry()?) {- Ok(()) => Ok(true),- Err(keyring::Error::NoEntry) => Ok(false),- Err(e) => Err(store_err(e)),- },+ Store::Keyring => {+ let existed = match vault_delete(keyring_entry()?) {+ Ok(()) => true,+ Err(keyring::Error::NoEntry) => false,+ Err(e) => return Err(store_err(e)),+ };+ // Signing out removes the item an older build left too.+ Ok(drop_legacy_item(KEYRING_ACCOUNT) || existed)+ }Store::TestKeychain(d) => match std::fs::remove_file(d.join("vault.json")) {Ok(()) => Ok(true),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),@@ -760,7 +798,9 @@ impl Store {adopt_read(&format!("{KEYRING_ACCOUNT}.{name}"), &s);Ok(Some(s))}- Err(keyring::Error::NoEntry) => Ok(None),+ Err(keyring::Error::NoEntry) => {+ move_legacy_item(&format!("{KEYRING_ACCOUNT}.{name}"))+ }Err(e) => Err(vault_err(e)),},_ => read_optional(&path),@@ -776,7 +816,13 @@ impl Store {}#[cfg(target_os = "macos")]{- vault_get(secret_entry(name).ok()?).ok()+ // A signed build that has not run since the service was renamed+ // has not moved the secret yet: it is still there under the+ // legacy name. This build only reads it, as it always does.+ vault_get(secret_entry(name).ok()?).ok().or_else(|| {+ let account = format!("{KEYRING_ACCOUNT}.{name}");+ vault_get(VaultEntry::new(legacy_keyring_service(), &account).ok()?).ok()+ })}#[cfg(not(target_os = "macos"))]{@@ -902,11 +948,14 @@ impl Store {let path = self.secret_path(name)?;match self {#[cfg(any(target_os = "macos", target_os = "windows"))]- Store::Keyring => match vault_delete(secret_entry(name)?) {- Ok(()) => Ok(true),- Err(keyring::Error::NoEntry) => Ok(false),- Err(e) => Err(store_err(e)),- },+ Store::Keyring => {+ let existed = match vault_delete(secret_entry(name)?) {+ Ok(()) => true,+ Err(keyring::Error::NoEntry) => false,+ Err(e) => return Err(store_err(e)),+ };+ Ok(drop_legacy_item(&format!("{KEYRING_ACCOUNT}.{name}")) || existed)+ }_ => match std::fs::remove_file(&path) {Ok(()) => Ok(true),Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),@@ -978,6 +1027,41 @@ fn adopt_read(account: &str, text: &str) {let _ = (account, text);}+/// Whether a vault account is a Cua item: the session or one of its named+/// secrets (`cua-cli`, `cua-cli.<name>`).+#[cfg(target_os = "macos")]+fn is_cua_account(account: &str) -> bool {+ account == KEYRING_ACCOUNT+ || account+ .strip_prefix(KEYRING_ACCOUNT)+ .is_some_and(|r| r.starts_with('.'))+}++/// The check of the current service's items together with what became of the+/// items moved from the legacy service ([`macos_keychain::migrate_legacy`]).+/// An item moved just now is read as the new item (and says so); one that+/// could not move is listed as the old item it is, so the check says the+/// keychain needs access, and the Spaces app offers to allow it.+#[cfg(target_os = "macos")]+fn merge_moved(+ mut items: Vec<(String, macos_keychain::ItemState)>,+ moved: Vec<(String, macos_keychain::ItemState)>,+) -> Vec<(String, macos_keychain::ItemState)> {+ use macos_keychain::ItemState;+ for (account, state) in moved {+ match items.iter_mut().find(|(a, _)| *a == account) {+ Some((_, found)) => {+ if state == (ItemState::Ready { recreated: true }) {+ *found = state;+ }+ }+ None => items.push((account, state)),+ }+ }+ items.sort_by(|a, b| a.0.cmp(&b.0));+ items+}+/// What [`Store::check_keychain`] found.#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]@@ -1287,11 +1371,21 @@ fn auth_failed(e: &keyring::Error) -> bool {/// macOS the item trusts every Cua executable of this machine, so the app,/// the daemon and the CLI share it without a keychain prompt (see/// `macos_keychain`).-#[cfg(target_os = "macos")]+#[cfg(any(target_os = "macos", target_os = "windows"))]fn vault_set(account: &str, text: &str) -> Result<()> {- let (account, text) = (account.to_string(), text.as_bytes().to_vec());+ vault_set_in(keyring_service(), account, text)+}++/// [`vault_set`] under another service name.+#[cfg(target_os = "macos")]+fn vault_set_in(service: &str, account: &str, text: &str) -> Result<()> {+ let (service, account, text) = (+ service.to_string(),+ account.to_string(),+ text.as_bytes().to_vec(),+ );keychain_call(- move || macos_keychain::set_generic_password(keyring_service(), &account, &text),+ move || macos_keychain::set_generic_password(&service, &account, &text),|| macos_keychain::Status(macos_keychain::ERR_SEC_INTERACTION_NOT_ALLOWED),).map_err(|e| {@@ -1306,8 +1400,8 @@ fn vault_set(account: &str, text: &str) -> Result<()> {}#[cfg(target_os = "windows")]-fn vault_set(account: &str, text: &str) -> Result<()> {- VaultEntry::new(keyring_service(), account)+fn vault_set_in(service: &str, account: &str, text: &str) -> Result<()> {+ VaultEntry::new(service, account).map_err(store_err)?.set_password(text).map_err(store_err)@@ -1390,6 +1484,76 @@ fn keyring_entry() -> Result<VaultEntry> {VaultEntry::new(keyring_service(), KEYRING_ACCOUNT).map_err(store_err)}+/// The OS credential vault as a [`legacy_vault::Vault`]: every call goes+/// through the same prompt-less, deadline-bound paths as an ordinary read or+/// write ([`vault_get`], [`vault_set_in`], [`vault_delete`]).+#[cfg(any(target_os = "macos", target_os = "windows"))]+struct NativeVault;++#[cfg(any(target_os = "macos", target_os = "windows"))]+impl legacy_vault::Vault for NativeVault {+ type Err = Error;++ fn read(&self, service: &str, account: &str) -> Result<Option<String>> {+ match vault_get(VaultEntry::new(service, account).map_err(store_err)?) {+ Ok(s) => Ok(Some(s)),+ Err(keyring::Error::NoEntry) => Ok(None),+ Err(e) => Err(vault_err(e)),+ }+ }++ fn write(&self, service: &str, account: &str, text: &str) -> Result<()> {+ vault_set_in(service, account, text)+ }++ fn delete(&self, service: &str, account: &str) -> Result<()> {+ match vault_delete(VaultEntry::new(service, account).map_err(store_err)?) {+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),+ Err(e) => Err(store_err(e)),+ }+ }+}++/// Moves the vault item `account` from the legacy service to the current+/// one (see [`legacy_vault`]) and returns its text; `None` when there is no+/// legacy item. A legacy item that needs a prompt this process may not show+/// stays as it is and fails with the usual hint ([`KEYCHAIN_NEEDS_ACCESS`]).+#[cfg(any(target_os = "macos", target_os = "windows"))]+fn move_legacy_item(account: &str) -> Result<Option<String>> {+ // A legacy recreate interrupted before its rename left the item under its+ // staging name: take it back first.+ #[cfg(target_os = "macos")]+ let _ = macos_keychain::recover_staged(+ macos_keychain::Keychain::Default,+ legacy_keyring_service(),+ account,+ );+ match legacy_vault::move_item(+ &NativeVault,+ legacy_keyring_service(),+ keyring_service(),+ account,+ ) {+ Ok(text) => Ok(text),+ Err(legacy_vault::Failure::Read(e) | legacy_vault::Failure::Write(e)) => Err(e),+ Err(legacy_vault::Failure::Unverified) => Err(Error::Store(+ "could not move the Cua sign-in to its new vault item; the old item was kept".into(),+ )),+ }+}++/// Deletes the legacy vault item `account` if there is one this process may+/// delete without a prompt (signing out never asks for a password because of+/// an item nobody uses any more); whether it did. Sign-out calls this next to+/// deleting the current item.+#[cfg(any(target_os = "macos", target_os = "windows"))]+fn drop_legacy_item(account: &str) -> bool {+ #[cfg(target_os = "macos")]+ let _quiet = macos_keychain::Quiet::new();+ VaultEntry::new(legacy_keyring_service(), account)+ .is_ok_and(|entry| vault_delete(entry).is_ok())+}+/// Whether a file store at `path` reads missing secrets from the OS/// credential vault: the default store of the real cua home, with no/// `CUA_CREDENTIAL_STORE` choice, outside tests.@@ -2718,6 +2882,55 @@ mod tests {assert!(!store.migrate_legacy(d.path()).unwrap());}+ #[cfg(any(target_os = "macos", target_os = "windows"))]+ #[test]+ fn the_session_lives_under_a_neutral_service_per_environment() {+ use cua_home::env::CuaEnv;+ assert_eq!(CuaEnv::Prod.keyring_service(), "ai.cua.session");+ assert_eq!(CuaEnv::Staging.keyring_service(), "ai.cua.session.staging");+ // The names older builds used are only ever read to move an item.+ assert_eq!(CuaEnv::Prod.legacy_keyring_service(), "run.cua.ai");+ assert_eq!(+ CuaEnv::Staging.legacy_keyring_service(),+ "staging.run.cua.ai"+ );+ for env in [CuaEnv::Prod, CuaEnv::Staging] {+ assert_ne!(env.keyring_service(), env.legacy_keyring_service());+ }+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn the_check_reports_moved_items_as_the_new_ones_and_blocked_ones_as_old() {+ use macos_keychain::ItemState as S;+ let ready = |recreated| S::Ready { recreated };+ // Moved just now: the check reads the new item and says it moved.+ assert_eq!(+ merge_moved(+ vec![("cua-cli".into(), ready(false))],+ vec![("cua-cli".into(), ready(true))]+ ),+ vec![("cua-cli".into(), ready(true))]+ );+ // The new session was there already; only the device key was blocked:+ // it is listed as needing access, in account order.+ assert_eq!(+ merge_moved(+ vec![("cua-cli".into(), ready(false))],+ vec![("cua-cli.device-key".into(), S::NeedsAccess)]+ ),+ vec![+ ("cua-cli".into(), ready(false)),+ ("cua-cli.device-key".into(), S::NeedsAccess)+ ]+ );+ // Nothing moved: the check as it was.+ assert_eq!(+ merge_moved(vec![("cua-cli".into(), ready(false))], vec![]),+ vec![("cua-cli".into(), ready(false))]+ );+ }+#[test]fn identity_prefers_the_id_token() {use base64::Engine;diff --git a/libs/cua/crates/cua-auth/src/macos_keychain.rs b/libs/cua/crates/cua-auth/src/macos_keychain.rsindex 8e213ef72e..b2c74d793f 100644--- a/libs/cua/crates/cua-auth/src/macos_keychain.rs+++ b/libs/cua/crates/cua-auth/src/macos_keychain.rs@@ -4,11 +4,11 @@//! Why: the legacy keychain gives a new generic password the default//! access list, which trusts only the executable that created it. The Cua//! Spaces app (`Contents/MacOS/CuaSpacesMac`) signs in and creates the-//! `run.cua.ai` / `cua-cli` item; the bundled `cua` daemon and CLI+//! `ai.cua.session` / `cua-cli` item; the bundled `cua` daemon and CLI//! (`Contents/MacOS/cua`, same Developer ID team, different executable)//! then read it and macOS asks for the login password ("cua wants to use-//! your confidential information stored in run.cua.ai"), right after every-//! first sign-in.+//! your confidential information stored in ..."), right after every first+//! sign-in.//!//! The fix keeps the default model (an explicit list of trusted//! applications, everyone else is asked) and only widens the list: the@@ -45,7 +45,29 @@//! [`check_items`] reads every Cua item without any prompt (user interaction//! disabled for the call) to tell "readable" from "needs a prompt", which//! the Spaces app asks before it starts anything that reads the session.-+//!+//! **Why the access list and not an access group.** An item shared by the+//! app and a `cua` installed outside it cannot use `kSecAttrAccessGroup`:+//! that is the data protection keychain, which needs the+//! `keychain-access-groups` entitlement backed by a provisioning profile, and+//! a bare command-line tool has no place to carry one (the Spaces app is+//! signed without any keychain access group on purpose). The file-based+//! login keychain is the one a Developer ID tool can use, and there Apple's+//! mechanism for "these applications may read this item without asking" is+//! the item's access list of trusted applications, each matched by its+//! designated requirement, together with the item's partition list, which+//! macOS sets to the creator's team (`teamid:YCK386LBJ7`) for a Developer ID+//! process. A process that meets both reads the item with no prompt, and+//! every later build with the same bundle id and team does.+//!+//! **Service rename (CUA-1877).** Items used to live under the service+//! `run.cua.ai`. [`migrate_legacy`] moves each one to the current service+//! with a read that never prompts (a Cua-signed build is trusted by the+//! legacy list, so it is silent), writes the new item with the access list+//! above, verifies it, and only then deletes the old one (see+//! `crate::legacy_vault`).++use crate::legacy_vault::{Failure, Vault, move_item};use core_foundation::base::TCFType as _;use security_framework::item::{ItemClass, ItemSearchOptions, Limit};use security_framework::os::macos::keychain::SecKeychain;@@ -175,6 +197,8 @@ const ERR_SEC_ITEM_NOT_FOUND: OSStatus = -25300;const ERR_SEC_AUTH_FAILED: OSStatus = -25293;/// `userCanceledErr`: the user cancelled the prompt.const USER_CANCELED: OSStatus = -128;+/// `errSecDecode`: an item whose secret is not text.+const ERR_SEC_DECODE: OSStatus = -26275;/// `errSecInteractionNotAllowed`: the keychain needs a prompt (unlock or/// access confirmation) that this session cannot show (an SSH session).pub(crate) const ERR_SEC_INTERACTION_NOT_ALLOWED: OSStatus = -25308;@@ -740,6 +764,88 @@ pub(crate) fn check_items(.collect()}+/// The keychain as a [`Vault`] of text items, for moving an item between+/// services: reads and the delete are as quiet as the caller made them+/// ([`Quiet`]); a write gives the item the Cua access list of this writer.+pub(crate) struct KeychainVault<'a> {+ pub(crate) kc: Keychain<'a>,+ pub(crate) signed: bool,+}++impl Vault for KeychainVault<'_> {+ type Err = Status;++ fn read(&self, service: &str, account: &str) -> Result<Option<String>, Status> {+ read_secret(self.kc, service, account)?+ .map(|bytes| String::from_utf8(bytes).map_err(|_| Status(ERR_SEC_DECODE)))+ .transpose()+ }++ fn write(&self, service: &str, account: &str, text: &str) -> Result<(), Status> {+ set_in(self.kc, service, account, text.as_bytes(), self.signed)+ }++ fn delete(&self, service: &str, account: &str) -> Result<(), Status> {+ match find_item(self.kc, service, account)? {+ None => Ok(()),+ Some(item) => check(unsafe { SecKeychainItemDelete(item.0) }),+ }+ }+}++/// Moves every item of `legacy_service` that `wanted` picks and `service`+/// lacks over to `service` (see [`crate::legacy_vault`]), and says what became+/// of each: `Ready { recreated: true }` when it moved, `NeedsAccess` when+/// reading the old item needs a prompt (without `prompt`, nothing is asked:+/// the old item is left as it is), `Denied` when the user refused it, and+/// `Failed` for anything else (the old item is left too). Items `service`+/// already has, and accounts the legacy service does not have, are not+/// listed.+pub(crate) fn migrate_legacy(+ kc: Keychain<'_>,+ legacy_service: &str,+ service: &str,+ wanted: &dyn Fn(&str) -> bool,+ prompt: bool,+ signed: bool,+) -> Vec<(String, ItemState)> {+ let _quiet = (!prompt).then(Quiet::new);+ let vault = KeychainVault { kc, signed };+ accounts(kc, legacy_service, wanted)+ .into_iter()+ .filter_map(|account| {+ match find_item(kc, service, &account) {+ // The current item wins; the old one is not touched.+ Ok(Some(_)) => return None,+ Ok(None) => {}+ Err(e) => return Some((account, ItemState::Failed(e.to_string()))),+ }+ let state = match move_item(&vault, legacy_service, service, &account) {+ Ok(Some(_)) => ItemState::Ready { recreated: true },+ // Gone since it was listed.+ Ok(None) => return None,+ Err(Failure::Read(Status(ERR_SEC_INTERACTION_NOT_ALLOWED))) => {+ ItemState::NeedsAccess+ }+ // As in `check_items`: with interaction disabled an access+ // list that would ask fails as "auth failed" (no one was+ // asked); after a prompt, it means the user denied it.+ Err(Failure::Read(Status(ERR_SEC_AUTH_FAILED))) if !prompt => {+ ItemState::NeedsAccess+ }+ Err(Failure::Read(Status(ERR_SEC_AUTH_FAILED | USER_CANCELED))) => {+ ItemState::Denied+ }+ Err(Failure::Read(e) | Failure::Write(e)) => ItemState::Failed(e.to_string()),+ Err(Failure::Unverified) => ItemState::Failed(+ "the moved item could not be read back; the old item was kept".into(),+ ),+ };+ Some((account, state))+ })+ .collect()+}+/// Whether this process's security session can show UI (a console login/// can; an SSH session cannot). `true` when unknown.pub(crate) fn has_graphic_access() -> bool {@@ -761,6 +867,7 @@ pub(crate) fn default_keychain_unlocked() -> Option<bool> {#[cfg(test)]mod tests {use super::*;+ use std::time::Duration;fn exe(p: &Path) {use std::os::unix::fs::PermissionsExt as _;@@ -1109,11 +1216,9 @@ mod tests {assert!(!recover_staged(t.at(), SERVICE, "cua-cli"));}- /// An item this process is not trusted by (another build wrote it):- /// with interaction disabled the check says so instead of prompting.- #[test]- fn an_untrusted_item_needs_access_without_a_prompt() {- let t = TestKeychain::new();+ /// An access list that trusts only `/usr/bin/true`: this process is not+ /// trusted by an item created with it, as with another build's item.+ fn access_for_another_app() -> Owned {let c = CString::new("/usr/bin/true").unwrap();let mut other: SecRef = ptr::null_mut();check(unsafe { SecTrustedApplicationCreateFromPath(c.as_ptr(), &mut other) }).unwrap();@@ -1130,7 +1235,15 @@ mod tests {let mut access: SecRef = ptr::null_mut();check(unsafe { SecAccessCreate(desc.0 as CFStringRef, list.0 as CFArrayRef, &mut access) }).unwrap();- let access = Owned(access);+ Owned(access)+ }++ /// An item this process is not trusted by (another build wrote it):+ /// with interaction disabled the check says so instead of prompting.+ #[test]+ fn an_untrusted_item_needs_access_without_a_prompt() {+ let t = TestKeychain::new();+ let access = access_for_another_app();create_with(t.at(),SERVICE,@@ -1146,4 +1259,367 @@ mod tests {// Nothing changed.assert_eq!(t.comment("cua-cli").as_deref(), Some("elsewhere"));}++ const LEGACY_SERVICE: &str = "legacy.cua.invalid";++ fn session_and_device_key(t: &TestKeychain, service: &str) {+ // As older builds wrote them: the default list, no comment.+ create_with(t.at(), service, "cua-cli", b"session", None).unwrap();+ create_with(t.at(), service, "cua-cli.device-key", b"key", None).unwrap();+ }++ fn exists(t: &TestKeychain, service: &str, account: &str) -> bool {+ find_item(t.at(), service, account).unwrap().is_some()+ }++ fn secret(t: &TestKeychain, service: &str, account: &str) -> Option<Vec<u8>> {+ read_secret(t.at(), service, account).unwrap()+ }++ /// Every item of the legacy service moves: the new one carries the Cua+ /// access list of the (Cua-signed) writer and the same secret, the old+ /// one is deleted, and nothing was asked.+ #[test]+ fn migration_moves_every_item_to_the_new_service_and_deletes_the_old_ones() {+ let t = TestKeychain::new();+ session_and_device_key(&t, LEGACY_SERVICE);+ let moved = migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true);+ assert_eq!(+ moved,+ vec![+ ("cua-cli".into(), ItemState::Ready { recreated: true }),+ (+ "cua-cli.device-key".into(),+ ItemState::Ready { recreated: true }+ ),+ ]+ );+ for (account, expected) in [("cua-cli", &b"session"[..]), ("cua-cli.device-key", b"key")] {+ assert_eq!(+ secret(&t, SERVICE, account).as_deref(),+ Some(expected),+ "{account}"+ );+ assert_eq!(t.comment(account).as_deref(), Some(ACL_MARKER), "{account}");+ assert!(!exists(&t, LEGACY_SERVICE, account), "{account} still old");+ // The writer (this process) is on the new item's list.+ let me = std::env::current_exe().unwrap().canonicalize().unwrap();+ assert!(+ trusted_paths(&t, account)+ .iter()+ .any(|p| p == me.to_str().unwrap()),+ "{account}"+ );+ }+ // The prompts switch is back on (the move was quiet, then restored).+ assert!(interaction_allowed());+ }++ #[test]+ fn migration_with_no_legacy_item_does_nothing() {+ let t = TestKeychain::new();+ assert!(migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true).is_empty());+ assert!(!exists(&t, SERVICE, "cua-cli"));+ // Other services' items and accounts nobody asked for stay put.+ create_with(t.at(), "other.invalid", "cua-cli", b"o", None).unwrap();+ create_with(t.at(), LEGACY_SERVICE, "unrelated", b"u", None).unwrap();+ let wanted = |a: &str| a.starts_with("cua-cli");+ assert!(migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &wanted, false, true).is_empty());+ assert!(exists(&t, "other.invalid", "cua-cli"));+ assert!(exists(&t, LEGACY_SERVICE, "unrelated"));+ assert!(!exists(&t, SERVICE, "cua-cli"));+ assert!(!exists(&t, SERVICE, "unrelated"));+ }++ /// A legacy item this process is not trusted by would need a prompt: the+ /// move reports it, creates nothing, and leaves the old item as it was.+ #[test]+ fn a_failed_read_leaves_the_old_item_intact() {+ let t = TestKeychain::new();+ let access = access_for_another_app();+ create_with(+ t.at(),+ LEGACY_SERVICE,+ "cua-cli",+ b"session",+ Some((&access, "elsewhere")),+ )+ .unwrap();+ // The device key is readable: a blocked item does not stop the others.+ create_with(t.at(), LEGACY_SERVICE, "cua-cli.device-key", b"key", None).unwrap();+ let moved = migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true);+ assert_eq!(+ moved,+ vec![+ ("cua-cli".into(), ItemState::NeedsAccess),+ (+ "cua-cli.device-key".into(),+ ItemState::Ready { recreated: true }+ ),+ ]+ );+ assert!(!exists(&t, SERVICE, "cua-cli"), "nothing was created");+ let old = find_item(t.at(), LEGACY_SERVICE, "cua-cli")+ .unwrap()+ .unwrap();+ assert_eq!(comment(&old).as_deref(), Some("elsewhere"));+ // The blocked move changed nothing, so it can be tried again: it+ // fails the same way and the old item is still there.+ assert_eq!(+ migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true),+ vec![("cua-cli".into(), ItemState::NeedsAccess)]+ );+ assert!(exists(&t, LEGACY_SERVICE, "cua-cli"));+ assert!(!exists(&t, SERVICE, "cua-cli"));+ }++ /// Moving again changes nothing, and an item the new service already+ /// has is never overwritten (nor is its legacy twin read or deleted).+ #[test]+ fn migration_is_idempotent_and_never_overwrites_the_new_item() {+ let t = TestKeychain::new();+ session_and_device_key(&t, LEGACY_SERVICE);+ let first = migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true);+ assert_eq!(first.len(), 2);+ assert!(migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true).is_empty());+ assert_eq!(+ secret(&t, SERVICE, "cua-cli").as_deref(),+ Some(&b"session"[..])+ );+ // A downgraded build wrote the legacy item again: the new one wins.+ create_with(t.at(), LEGACY_SERVICE, "cua-cli", b"older", None).unwrap();+ assert!(migrate_legacy(t.at(), LEGACY_SERVICE, SERVICE, &all, false, true).is_empty());+ assert_eq!(+ secret(&t, SERVICE, "cua-cli").as_deref(),+ Some(&b"session"[..])+ );+ assert_eq!(+ secret(&t, LEGACY_SERVICE, "cua-cli").as_deref(),+ Some(&b"older"[..])+ );+ }++ /// What a "build" does in [`a_second_signed_build_reads_the_item_without_a_prompt`]:+ /// a signed copy of this test binary runs only this test, with+ /// `CUA_KEYCHAIN_HELPER=<role>|<account>|<keychain path>`. Without the+ /// variable (every ordinary run) it does nothing.+ #[test]+ fn signed_build_helper() {+ let Ok(spec) = std::env::var("CUA_KEYCHAIN_HELPER") else {+ return;+ };+ let mut parts = spec.splitn(3, '|');+ let (role, account, path) = (+ parts.next().unwrap(),+ parts.next().unwrap(),+ parts.next().unwrap(),+ );+ let kc = SecKeychain::open(path).unwrap();+ let at = Keychain::Given(&kc);+ // Nothing in a helper may wait on a dialog.+ let _quiet = Quiet::new();+ match role {+ "create" => match set_in(at, SERVICE, account, b"session", true) {+ Ok(()) => println!("HELPER create ok"),+ Err(Status(code)) => println!("HELPER create error {code}"),+ },+ "create-legacy" => match set_in(at, LEGACY_SERVICE, account, b"session", true) {+ Ok(()) => println!("HELPER create-legacy ok"),+ Err(Status(code)) => println!("HELPER create-legacy error {code}"),+ },+ "migrate" => println!(+ "HELPER migrate {:?}",+ migrate_legacy(at, LEGACY_SERVICE, SERVICE, &|_| true, false, true)+ ),+ "delete" => match (KeychainVault {+ kc: at,+ signed: true,+ })+ .delete(SERVICE, account)+ {+ Ok(()) => println!("HELPER delete ok"),+ Err(Status(code)) => println!("HELPER delete error {code}"),+ },+ _ => match read_secret(at, SERVICE, account) {+ Ok(Some(s)) => println!("HELPER read ok {}", String::from_utf8_lossy(&s)),+ Ok(None) => println!("HELPER read none"),+ Err(Status(code)) => println!("HELPER read error {code}"),+ },+ }+ }++ /// Re-signs a copy of this test binary as a build named `ident`. With+ /// `dr`, its designated requirement is that text (what a Developer ID+ /// build has: the identifier and the team, not the code), else the+ /// ad hoc default (its cdhash, which changes with every build).+ /// `hardened` makes the code hash differ between builds of the same+ /// identifier. `None` when this machine cannot sign.+ fn signed_build(+ dir: &Path,+ file: &str,+ ident: &str,+ dr: Option<&str>,+ hardened: bool,+ ) -> Option<PathBuf> {+ let exe = dir.join(file);+ std::fs::copy(std::env::current_exe().ok()?, &exe).ok()?;+ let mut cmd = std::process::Command::new("/usr/bin/codesign");+ cmd.args(["--force", "-s", "-", "-i", ident]);+ if hardened {+ cmd.args(["-o", "runtime"]);+ }+ if let Some(dr) = dr {+ cmd.arg("-r").arg(format!("={dr}"));+ }+ let out = cmd.arg(&exe).output().ok()?;+ out.status.success().then_some(exe)+ }++ /// What the helper `build` printed for `role` on `keychain` (killed after+ /// a minute: a helper that waits on a dialog is a failure, not a hang).+ fn run_helper(build: &Path, role: &str, account: &str, keychain: &Path) -> String {+ let mut child = std::process::Command::new(build)+ .args([+ "--exact",+ "macos_keychain::tests::signed_build_helper",+ "--nocapture",+ "--test-threads=1",+ ])+ .env(+ "CUA_KEYCHAIN_HELPER",+ format!("{role}|{account}|{}", keychain.display()),+ )+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null())+ .spawn()+ .unwrap();+ let started = std::time::Instant::now();+ let status = loop {+ if let Some(status) = child.try_wait().unwrap() {+ break status;+ }+ if started.elapsed() > Duration::from_secs(60) {+ let _ = child.kill();+ return "HELPER timed out".into();+ }+ std::thread::sleep(Duration::from_millis(50));+ };+ let mut text = String::new();+ std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut text).unwrap();+ // libtest prints "test <name> ... " first on the same line.+ text.lines()+ .find_map(|l| l.find("HELPER ").map(|at| l[at..].trim().to_string()))+ .unwrap_or_else(|| format!("HELPER printed nothing ({status}): {text}"))+ }++ /// The point of the Cua access list: an item a signed build created is+ /// read, with prompts off, by a LATER signed build (other code, so+ /// another cdhash, same identifier), and by nothing else. The builds are+ /// ad hoc signed with a designated requirement of the identifier only,+ /// which is what a Developer ID build has across updates (its+ /// requirement names the identifier and the team, never the code). The+ /// control shows why an ordinary ad hoc build cannot hold such an item:+ /// its requirement is its cdhash, which the next build does not meet.+ ///+ /// Skipped (with a note) where `codesign` cannot run.+ #[test]+ fn a_second_signed_build_reads_the_item_without_a_prompt() {+ let t = TestKeychain::new();+ let kc_path = t._dir.path().join("test.keychain");+ let dir = tempfile::tempdir().unwrap();+ let dr = r#"designated => identifier "com.cua.keychain-test""#;+ let other_dr = r#"designated => identifier "com.cua.somebody-else""#;+ let ident = "com.cua.keychain-test";+ let (Some(v1), Some(v2), Some(other), Some(adhoc1), Some(adhoc2)) = (+ signed_build(dir.path(), "v1", ident, Some(dr), false),+ signed_build(dir.path(), "v2", ident, Some(dr), true),+ signed_build(+ dir.path(),+ "other",+ "com.cua.somebody-else",+ Some(other_dr),+ false,+ ),+ signed_build(dir.path(), "adhoc1", ident, None, false),+ signed_build(dir.path(), "adhoc2", ident, None, true),+ ) else {+ eprintln!("skipped: codesign cannot sign test builds here");+ return;+ };+ // A second build is another build: another cdhash.+ assert_ne!(std::fs::read(&v1).unwrap(), std::fs::read(&v2).unwrap());++ let created = run_helper(&v1, "create", "cua-cli", &kc_path);+ if created != "HELPER create ok" {+ eprintln!("skipped: a signed test build cannot use the keychain here ({created})");+ return;+ }+ assert_eq!(t.comment("cua-cli").as_deref(), Some(ACL_MARKER));+ let read = |who: &Path, account: &str| run_helper(who, "read", account, &kc_path);+ let needs_prompt = |got: &str| {+ got == format!("HELPER read error {ERR_SEC_INTERACTION_NOT_ALLOWED}")+ || got == format!("HELPER read error {ERR_SEC_AUTH_FAILED}")+ };+ if read(&v1, "cua-cli") != "HELPER read ok session" {+ eprintln!("skipped: a signed test build cannot read the keychain here");+ return;+ }+ // The build that wrote it reads it, and so does the later build,+ // with prompts off.+ assert_eq!(read(&v1, "cua-cli"), "HELPER read ok session");+ assert_eq!(read(&v2, "cua-cli"), "HELPER read ok session");+ // A build of another app would need a prompt.+ let got = read(&other, "cua-cli");+ assert!(needs_prompt(&got), "{got}");+ // The later build of the app can also delete it without a prompt:+ // that is what ends a move.+ assert_eq!(+ run_helper(&v2, "delete", "cua-cli", &kc_path),+ "HELPER delete ok"+ );+ assert!(!exists(&t, SERVICE, "cua-cli"));++ // The move across an update: the old build left the item under the+ // legacy service; the new build moves it with no prompt, the old+ // build still reads the new item, a stranger does not.+ assert_eq!(+ run_helper(&v1, "create-legacy", "cua-cli", &kc_path),+ "HELPER create-legacy ok"+ );+ assert_eq!(+ run_helper(&v2, "migrate", "-", &kc_path),+ r#"HELPER migrate [("cua-cli", Ready { recreated: true })]"#+ );+ assert!(!exists(&t, LEGACY_SERVICE, "cua-cli"));+ assert!(exists(&t, SERVICE, "cua-cli"));+ assert_eq!(t.comment("cua-cli").as_deref(), Some(ACL_MARKER));+ assert_eq!(read(&v1, "cua-cli"), "HELPER read ok session");+ let got = read(&other, "cua-cli");+ assert!(needs_prompt(&got), "{got}");+ // An item the new build cannot read without a prompt is not moved:+ // the old one stays as it was and nothing is created.+ let _ = run_helper(&v2, "delete", "cua-cli", &kc_path);+ assert_eq!(+ run_helper(&other, "create-legacy", "cua-cli", &kc_path),+ "HELPER create-legacy ok"+ );+ assert_eq!(+ run_helper(&v2, "migrate", "-", &kc_path),+ r#"HELPER migrate [("cua-cli", NeedsAccess)]"#+ );+ assert!(exists(&t, LEGACY_SERVICE, "cua-cli"));+ assert!(!exists(&t, SERVICE, "cua-cli"));++ // Control: an item an ordinary ad hoc build wrote is readable by+ // that build only, not by the next one, though both name the same+ // identifier.+ assert_eq!(+ run_helper(&adhoc1, "create", "adhoc-item", &kc_path),+ "HELPER create ok"+ );+ assert_eq!(read(&adhoc1, "adhoc-item"), "HELPER read ok session");+ let got = read(&adhoc2, "adhoc-item");+ assert!(needs_prompt(&got), "{got}");+ }}diff --git a/libs/cua/crates/cua-home/src/env.rs b/libs/cua/crates/cua-home/src/env.rsindex 237a5363c9..89f94b1a63 100644--- a/libs/cua/crates/cua-home/src/env.rs+++ b/libs/cua/crates/cua-home/src/env.rs@@ -130,9 +130,23 @@ impl CuaEnv {}}- /// The OS credential vault service the session is stored under- /// (production keeps `run.cua.ai`).+ /// The OS credential vault service the session, the device key and the+ /// other named secrets are stored under. The name is neutral on purpose:+ /// it used to be the retired Cloud API host (see+ /// [`CuaEnv::legacy_keyring_service`]).pub fn keyring_service(self) -> &'static str {+ match self {+ Self::Prod => "ai.cua.session",+ Self::Staging => "ai.cua.session.staging",+ }+ }++ /// The service older builds stored the session under (the retired Cloud+ /// API host). Builds that use [`CuaEnv::keyring_service`] move an item+ /// they find here once, then delete it. Remove this, and the move in+ /// `cua-auth`, two releases or 60 days after the first release that has+ /// the move, whichever is later (CUA-1877).+ pub fn legacy_keyring_service(self) -> &'static str {match self {Self::Prod => "run.cua.ai",Self::Staging => "staging.run.cua.ai",@@ -278,7 +292,8 @@ mod tests {assert_eq!(e.spaces_api_url, "https://api.cua.ai");assert_eq!(e.account_app_url, "https://app.cua.ai");assert_eq!(e.spaces_site_url, "https://cua.ai");- assert_eq!(CuaEnv::Prod.keyring_service(), "run.cua.ai");+ assert_eq!(CuaEnv::Prod.keyring_service(), "ai.cua.session");+ assert_eq!(CuaEnv::Prod.legacy_keyring_service(), "run.cua.ai");assert_eq!(CuaEnv::Prod.home_subdir(), None);// An unknown value never selects staging.assert_eq!(endpoints(&[("CUA_ENV", "stagign")]), e);@@ -296,7 +311,11 @@ mod tests {assert_eq!(e.spaces_api_url, "https://api.staging.cua.ai");assert_eq!(e.account_app_url, "https://app.staging.cua.ai");assert_eq!(e.spaces_site_url, "https://spaces.staging.cua.ai");- assert_eq!(CuaEnv::Staging.keyring_service(), "staging.run.cua.ai");+ assert_eq!(CuaEnv::Staging.keyring_service(), "ai.cua.session.staging");+ assert_eq!(+ CuaEnv::Staging.legacy_keyring_service(),+ "staging.run.cua.ai"+ );assert_eq!(CuaEnv::Staging.home_subdir(), Some("envs/staging"));}diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rsindex 7c2904d413..17b8c908a2 100644--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs@@ -3,7 +3,7 @@//!//! The keys live in the OS credential vault through cua-auth's secret store//! ([`cua_auth::Store::save_secret`]): one item, `agent-keys`, next to the-//! session (service `run.cua.ai`), with the same access list, so the app,+//! session (service `ai.cua.session`), with the same access list, so the app,//! the daemon and the CLI read it without a prompt. A build whose store is//! a file (an unsigned macOS build, Linux) refuses to save them: keys are//! never written to a plain file. Set the key in the daemon's environment