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.

feat(spaces): Local dev builds keep agent keys in a private file without the Keychain; install-local.sh signs with its own Keychain (#6587)

ddupontffa4c068ac24
diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.ts
index 1c058d60ca..0a2f29db41 100644
--- a/apps/cua-spaces-desktop/src/model/agents.ts
+++ b/apps/cua-spaces-desktop/src/model/agents.ts
@@ -407,7 +407,8 @@ export function agentKeysInput(report: Json | null, error: string | null): AppAg
}))
.filter((k) => k.env !== "");
const unavailable = report?.available === false ? (typeof report.unavailable === "string" ? report.unavailable : "this machine can't keep keys") : undefined;
- return { keys, unavailable, error: error ?? undefined };
+ const warning = report?.available !== false && typeof report?.insecure === "string" && report.insecure ? report.insecure : undefined;
+ return { keys, unavailable, warning, error: error ?? undefined };
}
// MARK: Coding agents on this machine
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 0521064d4e..b5fddf9a38 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -9038,6 +9038,12 @@ export type AppAgentKeysInput = {
* Why this machine can't keep keys (the daemon's words), when it can't.
*/
unavailable?: string,
+ /**
+ * Keys can be saved but only in an unencrypted file (a Local
+ * development build without the Keychain): the daemon's warning, shown
+ * in the notice while the buttons stay on.
+ */
+ warning?: string,
/**
* The keys could not be read (no daemon, a refused Keychain).
*/
@@ -9067,17 +9073,20 @@ const FfiConverterTypeAppAgentKeysInput = (() => {
return {
keys: FfiConverterSequenceTypeAppAgentKeyInput.read(from),
unavailable: FfiConverterOptionalString.read(from),
+ warning: FfiConverterOptionalString.read(from),
error: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterSequenceTypeAppAgentKeyInput.write(value.keys, into);
FfiConverterOptionalString.write(value.unavailable, into);
+ FfiConverterOptionalString.write(value.warning, into);
FfiConverterOptionalString.write(value.error, into);
}
allocationSize(value: TypeName): number {
return FfiConverterSequenceTypeAppAgentKeyInput.allocationSize(value.keys) +
FfiConverterOptionalString.allocationSize(value.unavailable) +
+ FfiConverterOptionalString.allocationSize(value.warning) +
FfiConverterOptionalString.allocationSize(value.error);
}
diff --git a/apps/cua-spaces-desktop/test/agents-fixtures.ts b/apps/cua-spaces-desktop/test/agents-fixtures.ts
index bc1e344c45..c51812ba8d 100644
--- a/apps/cua-spaces-desktop/test/agents-fixtures.ts
+++ b/apps/cua-spaces-desktop/test/agents-fixtures.ts
@@ -87,6 +87,8 @@ export class FakeAgentKeysTools {
keys: Record<string, unknown>[] = [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", added_ms: 1_790_000_000_000 }];
uses: Record<string, Record<string, unknown>> = {};
available = true;
+ /** A Local development build keeping keys in an unencrypted file: the daemon's warning. */
+ insecure: string | null = null;
run: ToolRunner = async (tool, args) => {
this.calls.push([tool, args]);
@@ -133,6 +135,7 @@ export class FakeAgentKeysTools {
}
const report: Record<string, unknown> = { keys: this.keys, providers: [], available: this.available, ...(Object.keys(this.uses).length ? { uses: this.uses } : {}) };
if (!this.available) report.unavailable = "this build keeps credentials in a file";
+ if (this.insecure) report.insecure = this.insecure;
return report;
};
}
diff --git a/apps/cua-spaces-desktop/test/agents.test.ts b/apps/cua-spaces-desktop/test/agents.test.ts
index 7535a99eb0..482b0b3a11 100644
--- a/apps/cua-spaces-desktop/test/agents.test.ts
+++ b/apps/cua-spaces-desktop/test/agents.test.ts
@@ -437,6 +437,15 @@ describe.skipIf(!built)("agents", () => {
expect(ok.env).toBe("GEMINI_API_KEY");
});
+ it("warns that a development build keeps keys unencrypted and keeps the buttons on", async () => {
+ keys.insecure = "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets";
+ const { model } = makeBridge();
+ await model.agents.keys.load();
+ expect(model.agents.keys.view.canEdit).toBe(true);
+ expect(model.agents.keys.view.notice).toContain("Keychain not available in this development build");
+ expect(agentKeysInput({ keys: [], available: false, insecure: "x" }, null).warning).toBeUndefined();
+ });
+
it("says why keys can't be saved", async () => {
keys.available = false;
const { model } = makeBridge();
diff --git a/apps/cua-spaces-macos/README.md b/apps/cua-spaces-macos/README.md
index 626d860ba4..097cc8ab1f 100644
--- a/apps/cua-spaces-macos/README.md
+++ b/apps/cua-spaces-macos/README.md
@@ -387,6 +387,18 @@ the app is signed ad hoc and macOS asks for Screen Recording and Accessibility
again after every rebuild; the script says so, and clears the stale rows for the
Local bundle id only. `--require-stable-signing` stops instead of signing ad hoc.
+The certificate lives in a Keychain the script owns,
+`~/Library/Keychains/cua-spaces-local-signing.keychain-db`, with an empty password
+(it only signs development builds of Cua Spaces Local on this Mac), so a locked
+login Keychain, SSH or a VM does not stop it and nothing is asked to unlock it. The
+script writes nothing to your login Keychain and leaves the search list alone; it
+keeps using a stable local certificate that is already in the login Keychain, or the
+`cua-driver-signing` Keychain of Cua Driver's local install, so permissions already
+granted survive. `CUA_LOCAL_SIGNING_OWN_KEYCHAIN=0` turns the owned Keychain off. When
+nothing works the app is signed ad hoc and the script says why in one line, with the
+command to run (`--setup-signing` for the one-time trust prompt, or
+`security unlock-keychain ...` when an SSH session left the Keychain locked).
+
On a new Keychain the certificate is created but codesign cannot use it until
macOS trusts it for code signing, its Keychain is in your search list and
codesign may use its key. The script checks that with a real signing. When it
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
index 5054cd5c61..9170da6635 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
@@ -84,7 +84,8 @@ public final class AgentKeysModel {
}
let unavailable = report?["available"] as? Bool == false
? (report?["unavailable"] as? String ?? "this machine can't keep keys") : nil
- return AppAgentKeysInput(keys: keys.filter { !$0.env.isEmpty }, unavailable: unavailable, error: error)
+ let warning = report?["available"] as? Bool != false ? (report?["insecure"] as? String).flatMap { $0.isEmpty ? nil : $0 } : nil
+ return AppAgentKeysInput(keys: keys.filter { !$0.env.isEmpty }, unavailable: unavailable, warning: warning, error: error)
}
public var view: AppAgentKeysView { appAgentKeysView(input: input) }
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
index a9d0dacf59..fe96411a11 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/AgentKeysTests.swift
@@ -14,6 +14,8 @@ final class FakeAgentKeysTools: AgentsToolRunning, @unchecked Sendable {
var calls: [(String, [String: Any])] = []
var keys: [[String: Any]] = [["provider": "openai", "env": "OPENAI_API_KEY", "last4": "3f9a", "added_ms": 1_790_000_000_000]]
var available = true
+ /// A Local development build keeping keys in an unencrypted file: the daemon's warning.
+ var insecure: String?
func agentsTool(_ tool: String, _ args: [String: Any]) async throws -> Any {
calls.append((tool, args))
@@ -43,6 +45,7 @@ final class FakeAgentKeysTools: AgentsToolRunning, @unchecked Sendable {
}
var report: [String: Any] = ["keys": keys, "providers": [], "available": available]
if !available { report["unavailable"] = "this build keeps credentials in a file" }
+ if let insecure { report["insecure"] = insecure }
return report
}
}
@@ -94,6 +97,21 @@ struct AgentKeysTests {
#expect(none.view.notice?.contains("need the cua daemon") == true)
}
+ @Test func aDevelopmentBuildWarnsThatKeysAreUnencryptedAndKeepsTheButtonsOn() async {
+ let tools = FakeAgentKeysTools()
+ tools.insecure = "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets"
+ let m = AgentKeysModel(tools: tools)
+ await m.load()
+ #expect(m.view.canEdit)
+ #expect(m.view.notice?.hasPrefix("Keychain not available in this development build") == true)
+ #expect(m.view.notice?.contains("unencrypted") == true)
+ // A refusal still wins over the warning.
+ tools.available = false
+ await m.load()
+ #expect(!m.view.canEdit)
+ #expect(m.view.notice?.hasPrefix("Keys can't be saved here") == true)
+ }
+
@Test func aKeyFromYourShellIsSavedAndTheNamesNeverReplaceTheList() async throws {
let tools = FakeAgentKeysTools()
let m = AgentKeysModel(tools: tools)
diff --git a/apps/cua-spaces-macos/scripts/install-local.sh b/apps/cua-spaces-macos/scripts/install-local.sh
index 4cfd6dbc38..0371653a38 100755
--- a/apps/cua-spaces-macos/scripts/install-local.sh
+++ b/apps/cua-spaces-macos/scripts/install-local.sh
@@ -62,8 +62,8 @@
# macOS asks for the renamed app's permissions once; the old id's permission rows
# stay in macOS's list (macOS cannot clear them for an app that is gone), unused.
#
-# Signing: the stable local certificate shared with Cua Driver's local install
-# (libs/cua-driver/scripts/_local-signing.sh), so the Screen Recording and
+# Signing: a stable local certificate (the one Cua Driver's local install
+# makes, libs/cua-driver/scripts/_local-signing.sh), so the Screen Recording and
# Accessibility grants of Cua Spaces Local survive a rebuild. Without it the
# bundle is signed ad hoc and the grants reset on every rebuild (reported).
# On a fresh Keychain the certificate is created, but codesign cannot use it
@@ -76,6 +76,15 @@
# terminal, no screen) it prints the exact commands instead. It never trusts
# anything without that, never changes which certificate is used, and a
# certificate-backed signature is still what it checks for.
+# The certificate lives in a Keychain this script owns,
+# ~/Library/Keychains/cua-spaces-local-signing.keychain-db (empty password, so
+# nothing is asked to unlock it and a locked login Keychain does not matter).
+# It writes nothing to your login Keychain; it reuses a certificate already
+# there, or the Keychain Cua Driver's local install made, as before.
+# By default it signs ad hoc (no certificate, no Keychain prompt at all);
+# CUA_LOCAL_SIGN=stable, --setup-signing or --require-stable-signing use the
+# stable certificate. CUA_LOCAL_SIGN=adhoc forces ad hoc. CUA_LOCAL_SIGNING_OWN_KEYCHAIN=0 turns the own Keychain off. When nothing works the app is
+# signed ad hoc and the script says why in one line.
#
# Uninstall: scripts/uninstall-local.sh.
set -euo pipefail
@@ -124,6 +133,17 @@ while [ "$#" -gt 0 ]; do
shift
done
+# Ad hoc signing is the default: no certificate, no Keychain, no prompt. The
+# stable certificate (permissions that survive rebuilds) is opt-in with
+# --setup-signing, --require-stable-signing or CUA_LOCAL_SIGN=stable.
+if [ -z "${CUA_LOCAL_SIGN:-}" ]; then
+ if [ "$SETUP_SIGNING" = 1 ] || [ "$REQUIRE_STABLE_SIGNING" = 1 ]; then
+ CUA_LOCAL_SIGN=stable
+ else
+ CUA_LOCAL_SIGN=adhoc
+ fi
+fi
+
if [ "$(id -u)" -eq 0 ] || [ -n "${SUDO_USER:-}" ]; then
die "do not run this script with sudo or as root."
fi
@@ -514,6 +534,81 @@ signing_probe_locked() {
return 1
}
+# The Keychain this script owns for the stable local certificate. Its password
+# is empty on purpose: the certificate only signs development builds of Cua
+# Spaces Local on this Mac, and an empty password lets the script unlock it
+# anywhere (SSH, a VM) without asking. It is never the login Keychain.
+OWNED_SIGNING_KEYCHAIN="$HOME/Library/Keychains/cua-spaces-local-signing.keychain-db"
+OWNED_SIGNING=0
+OWNED_SIGNING_ERROR=""
+
+# Whether the login Keychain is locked and cannot be asked to unlock (an SSH
+# session): only looked at there, so nothing ever opens an unlock window.
+login_keychain_locked() {
+ local login="$HOME/Library/Keychains/login.keychain-db" rc=0
+ [ -n "${SSH_CONNECTION:-}" ] && [ -f "$login" ] || return 1
+ security_bounded 5 find-generic-password -s cua-local-lock-probe "$login" >/dev/null 2>&1 || rc=$?
+ [ "$rc" != 0 ] && [ "$rc" != 44 ]
+}
+security_bounded() {
+ local seconds="$1"
+ shift
+ perl -e 'alarm shift; exec @ARGV' "$seconds" security "$@"
+}
+
+# Picks the Keychain the stable local certificate is made in, unless something
+# already decides it: CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN or _IDENTITY (your
+# choice), the dedicated Keychain of Cua Driver's local install, or a stable
+# local certificate already in the login Keychain (it keeps signing as before,
+# so permissions granted to it survive). Otherwise it creates and unlocks its
+# own Keychain and points the shared helpers at it. Never writes to the login
+# Keychain and never changes the Keychain search list.
+choose_signing_keychain() {
+ local login="$HOME/Library/Keychains/login.keychain-db"
+ [ "$OS" = Darwin ] && command -v security >/dev/null 2>&1 || return 0
+ [ "${CUA_LOCAL_SIGNING_OWN_KEYCHAIN:-1}" != 0 ] || return 0
+ [ -z "${CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN:-}" ] || return 0
+ [ -z "${CUA_DRIVER_LOCAL_SIGNING_IDENTITY:-}" ] || return 0
+ [ ! -f "$HOME/Library/Keychains/cua-driver-signing.keychain-db" ] || return 0
+ if [ -f "$login" ] && security find-certificate -c "$CUA_LOCAL_SIGN_CN" "$login" >/dev/null 2>&1; then
+ return 0
+ fi
+ OWNED_SIGNING=1
+ # Whatever happens next, the shared helpers must not fall back to the login Keychain.
+ export CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN="$OWNED_SIGNING_KEYCHAIN"
+ if [ ! -f "$OWNED_SIGNING_KEYCHAIN" ]; then
+ mkdir -p "$(dirname "$OWNED_SIGNING_KEYCHAIN")" 2>/dev/null || true
+ if ! OWNED_SIGNING_ERROR="$(security create-keychain -p "" "$OWNED_SIGNING_KEYCHAIN" 2>&1)"; then
+ return 0
+ fi
+ # create-keychain may add the new one to the search list on some
+ # macOS versions; this script leaves the list as it found it.
+ fi
+ # No auto-lock timeout, then unlock it (a no-op when it is open).
+ security set-keychain-settings "$OWNED_SIGNING_KEYCHAIN" >/dev/null 2>&1 || true
+ if ! OWNED_SIGNING_ERROR="$(security unlock-keychain -p "" "$OWNED_SIGNING_KEYCHAIN" 2>&1)"; then
+ return 0
+ fi
+ OWNED_SIGNING_ERROR=""
+}
+
+# The one line that says why the app is signed ad hoc, and what to run.
+ad_hoc_reason() {
+ local kc
+ kc="$(local_signing_keychain)"
+ if [ "$OWNED_SIGNING" = 1 ] && [ -n "$OWNED_SIGNING_ERROR" ]; then
+ printf 'the script could not set up its signing Keychain (%s): %s' "$OWNED_SIGNING_KEYCHAIN" "$(printf '%s' "$OWNED_SIGNING_ERROR" | head -n 1)"
+ elif login_keychain_locked; then
+ printf 'the login Keychain is locked in this SSH session: run security unlock-keychain "%s/Library/Keychains/login.keychain-db" and build again' "$HOME"
+ elif [ "$SIGNING_PROBLEM" = locked ] || [ "$SIGNING_PROBLEM" = no-certificate ]; then
+ printf 'the Keychain %s is locked: run security unlock-keychain "%s" and build again' "$kc" "$kc"
+ elif [ -n "${CUA_DRIVER_LOCAL_SIGNING_IDENTITY:-}" ]; then
+ printf 'codesign cannot use the identity you chose (CUA_DRIVER_LOCAL_SIGNING_IDENTITY)'
+ else
+ printf 'macOS does not trust the local signing certificate yet: run scripts/install-local.sh --setup-signing once (one password prompt)'
+ fi
+}
+
# Whether the Keychain exists but holds no stable local certificate although the
# script just tried to create one (the shared helper swallows why it could not).
signing_certificate_missing() {
@@ -565,9 +660,14 @@ print_signing_bootstrap() {
if ! keychain_listed "$kc"; then
echo " security list-keychains -d user -s \"$kc\" \"$HOME/Library/Keychains/login.keychain-db\"" >&2
fi
- echo " read -r -s -p 'Keychain password: ' KCPW; echo" >&2
- echo " security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"$CUA_LOCAL_SIGN_CN\" -k \"\$KCPW\" \"$kc\" >/dev/null; unset KCPW" >&2
- echo " (-l limits it to that certificate's key; do not drop it: without it every signing key in the Keychain is changed)" >&2
+ if [ "$OWNED_SIGNING" = 1 ]; then
+ # The script's own Keychain has an empty password and the script opens the key itself.
+ echo " security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"$CUA_LOCAL_SIGN_CN\" -k \"\" \"$kc\" >/dev/null" >&2
+ else
+ echo " read -r -s -p 'Keychain password: ' KCPW; echo" >&2
+ echo " security set-key-partition-list -S apple-tool:,apple:,codesign: -s -t private -l \"$CUA_LOCAL_SIGN_CN\" -k \"\$KCPW\" \"$kc\" >/dev/null; unset KCPW" >&2
+ echo " (-l limits it to that certificate's key; do not drop it: without it every signing key in the Keychain is changed)" >&2
+ fi
echo "then run this script again, or run it with --setup-signing and it does this for you." >&2
}
@@ -694,7 +794,11 @@ make_signing_identity_usable() {
return 0
fi
# 3. codesign may use the key without a prompt. Needs the Keychain's
- # password: asked here, used once, not stored.
+ # password: asked here, used once, not stored (ours has none).
+ if [ "$OWNED_SIGNING" = 1 ] && open_key_to_codesign "$kc" "" && signing_probe "$identity" "$macho"; then
+ ok "codesign can use the stable local certificate"
+ return 0
+ fi
if [ -t 0 ]; then
printf 'Password of the Keychain %s (used once, not stored): ' "$kc"
read -r -s pw || pw=""
@@ -721,10 +825,20 @@ make_signing_identity_usable() {
# has the certificate (never swap a working signature for an ad hoc one).
sign_staged_app() {
local app_stage="$1" app_dest="$2" sign_id requirement
- sign_id="$(ensure_local_signing_identity)"
+ # CUA_LOCAL_SIGN=adhoc: sign ad hoc and never look for, create or use a
+ # certificate, so codesign never asks for a Keychain key ("codesign wants to
+ # access key id"). The grants then reset on each rebuild.
+ if [ "${CUA_LOCAL_SIGN:-}" = adhoc ]; then
+ sign_id="-"
+ else
+ choose_signing_keychain
+ sign_id="$(ensure_local_signing_identity)"
+ fi
if [ "$sign_id" != "-" ]; then
+ # Our own Keychain has an empty password: codesign may use the key now.
+ if [ "$OWNED_SIGNING" = 1 ]; then open_key_to_codesign "$OWNED_SIGNING_KEYCHAIN" "" || true; fi
make_signing_identity_usable "$sign_id" "$app_stage" || true
- elif signing_certificate_missing; then
+ elif [ "${CUA_LOCAL_SIGN:-}" != adhoc ] && signing_certificate_missing; then
SIGNING_PROBLEM=no-certificate
warn "could not create the stable local certificate in $(local_signing_keychain): the Keychain is probably locked."
fi
@@ -770,7 +884,7 @@ sign_staged_app() {
err "could not verify the staged app's ad hoc requirement; the installed app was not changed."
return 1
fi
- warn "$LOCAL_APP_DIR_NAME is signed ad hoc: its Screen Recording and Accessibility grants reset on the next rebuild."
+ warn "$LOCAL_APP_DIR_NAME is signed ad hoc because $(ad_hoc_reason). Its Screen Recording and Accessibility grants reset on the next rebuild."
print_signing_bootstrap
}
diff --git a/apps/cua-spaces-macos/scripts/tests/install-local-test.sh b/apps/cua-spaces-macos/scripts/tests/install-local-test.sh
index 16e0f7f14b..e54f5bbc63 100755
--- a/apps/cua-spaces-macos/scripts/tests/install-local-test.sh
+++ b/apps/cua-spaces-macos/scripts/tests/install-local-test.sh
@@ -378,6 +378,12 @@ run() {
export HOME="$FAKE_HOME" PATH="$SHIMS:$PATH" CUA_LSREGISTER="$SHIMS/lsregister" \
SHIM_LOG SHIM_STATE STUB_LOG FAKE_BUILD_LOG="$BUILD_LOG" FAKE_STUB="$STUB_BIN" \
FAKE_DYLIB="$STUB_DYLIB" LUME_LOG CARGO_LOG WEB_LOG FAKE_CHECKOUT_DAEMON="$DAEMON_CHECKOUT" FAKE_PINNED_DAEMON="$DAEMON_PINNED"
+ # The own signing Keychain of the script is off unless a test turns it on:
+ # these tests shim the login Keychain.
+ export CUA_LOCAL_SIGNING_OWN_KEYCHAIN="${TEST_OWN_KEYCHAIN:-0}"
+ # The shipped default is ad hoc (no Keychain); the older tests cover the
+ # stable certificate path, so they opt into it unless a test sets TEST_SIGN.
+ export CUA_LOCAL_SIGN="${TEST_SIGN:-stable}"
# CI is set on a CI runner and not on a Mac. The web UI check expects
# CI=true only where install-local.sh sets it (pnpm install), so drop it.
unset SUDO_USER CUA_DRIVER_LOCAL_SIGNING_KEYCHAIN CUA_DRIVER_LOCAL_SIGNING_IDENTITY CUA_CHANNEL CUA_HOME CUA_ENV \
@@ -594,6 +600,17 @@ check "an ad hoc cdhash change resets the Local TCC rows, and only those" \
check "Stable files are byte-identical after a rebuild" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'
check "nothing but the Local app changed" '[ "$(snap_all | grep -v "Cua Spaces Local.app")" = "$(printf "%s\n" "$ALL_BEFORE" | grep -v "Cua Spaces Local.app")" ]'
+echo "== default signing is ad hoc: no Keychain is asked for anything =="
+reset_fixture
+: > "$SHIM_LOG"
+run env -u CUA_LOCAL_SIGN "$FAKE_SCRIPTS/install-local.sh" --no-launch
+check "a plain install-local.sh run succeeds (status $RC)" '[ "$RC" = 0 ]'
+check "a plain run makes no security(1) call that reads or writes a Keychain item (only the read-only list-keychains)" \
+ '! grep "^security " "$SHIM_LOG" | grep -v "^security list-keychains " | grep >/dev/null .'
+check "a plain run says it signed ad hoc" 'printf "%s" "$OUT" | grep -i >/dev/null "ad hoc"'
+check "the ad hoc signature verifies" '/usr/bin/codesign --verify --deep --strict "$LOCAL_APP" 2>/dev/null'
+reset_fixture
+
# --- 3. Launch and --prefix ----------------------------------------------------------------
echo "== launch, prefix =="
@@ -1222,6 +1239,33 @@ check "a certificate codesign can already use: no warning and no setup" \
'! printf "%s" "$OUT" | grep -F >/dev/null "codesign cannot use" && ! security_calls | grep >/dev/null -e "add-trusted-cert" -e "set-key-partition-list"'
check "the Stable files are untouched by all of this" '[ "$(snap_stable)" = "$(snap_stable)" ] && [ ! -e "$FAKE_HOME/.cua-local" ]'
+# The script's own signing Keychain, on the real `security` and `codesign` but
+# under the fake HOME: it makes ~/Library/Keychains/cua-spaces-local-signing.keychain-db
+# there, never a login Keychain, and signs ad hoc with one line saying why when
+# macOS does not trust the new certificate yet (a unit test must not change trust).
+echo "== the script's own signing Keychain =="
+if command -v openssl >/dev/null 2>&1; then
+ OWN_KC="$FAKE_HOME/Library/Keychains/cua-spaces-local-signing.keychain-db"
+ own_install() { TEST_OWN_KEYCHAIN=1 run env SHIM_SECURITY_PASSTHROUGH=1 "$FAKE_SCRIPTS/install-local.sh" --no-launch "$@"; }
+ reset_fixture
+ STABLE_BEFORE="$(snap_stable)"
+ own_install
+ check "it makes its own Keychain (status $RC)" '[ "$RC" = 0 ] && [ -f "$OWN_KC" ]'
+ check "it never creates or writes the login Keychain" '[ ! -e "$FAKE_HOME/Library/Keychains/login.keychain-db" ] && [ ! -e "$FAKE_HOME/Library/Keychains/login.keychain" ]'
+ check "the certificate is in its Keychain" '/usr/bin/security find-certificate -c "CuaDriver Local Signing (cua-driver-rs)" "$OWN_KC" >/dev/null 2>&1'
+ check "untrusted, it signs ad hoc and says why in one line, with what to run" \
+ 'printf "%s" "$OUT" | grep -F >/dev/null "is signed ad hoc because macOS does not trust the local signing certificate yet: run scripts/install-local.sh --setup-signing once" && [ -d "$LOCAL_APP" ]'
+ check "the Stable files are untouched" '[ "$(snap_stable)" = "$STABLE_BEFORE" ]'
+ reset_fixture
+ own_install --require-stable-signing
+ check "--require-stable-signing with an untrusted certificate stops and installs nothing" '[ "$RC" != 0 ] && [ ! -e "$LOCAL_APP" ]'
+ reset_fixture
+ run env CUA_LOCAL_SIGNING_OWN_KEYCHAIN=0 SHIM_SECURITY_PASSTHROUGH=0 "$FAKE_SCRIPTS/install-local.sh" --no-launch
+ check "CUA_LOCAL_SIGNING_OWN_KEYCHAIN=0 makes no Keychain of its own" '[ ! -e "$OWN_KC" ]'
+else
+ note "SKIP: no openssl for the own-Keychain checks"
+fi
+
# The stable local certificate itself (shared with Cua Driver's local install)
# needs a code-signing identity that codesign can use without a prompt, from a
# keychain in the real search list (which a fake HOME hides). Only a Mac set up
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys.test.tsx b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys.test.tsx
index 6b503ee54d..2f5e61d83a 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/agent-keys.test.tsx
+++ b/apps/cua-spaces-web/src/bridge/__tests__/agent-keys.test.tsx
@@ -7,7 +7,7 @@ import { createDemoAdapter } from "../adapters/demo";
import type { CoreClient } from "../core";
import { BridgeProvider, useAgentKeys, type AgentKeysHook } from "../index";
import { agentKeysFromWire, tauriAgentKeysOps, webkitAgentKeysOps } from "../ops/agent-keys";
-import { agentKeyForm, agentKeyNameProblemOf } from "../agent-keys";
+import { agentKeyForm, agentKeyNameProblemOf, agentKeysInputOf } from "../agent-keys";
import { replayFlow } from "../parity";
import { noCore, testCore, wasmBuilt } from "./testCore";
@@ -40,6 +40,16 @@ describe("agent key operations", () => {
expect(agentKeysFromWire(null).keys).toEqual([]);
});
+ it("carries the unencrypted-file warning of a Local development build into the core's input", () => {
+ const warning = "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets";
+ const r = agentKeysFromWire({ ...WIRE, insecure: warning });
+ expect(r).toMatchObject({ available: true, insecure: warning });
+ expect(agentKeysInputOf(r, null)).toMatchObject({ unavailable: null, warning });
+ // A normal report has no warning, and a refusal never carries one.
+ expect(agentKeysInputOf(agentKeysFromWire(WIRE), null)).not.toHaveProperty("warning");
+ expect(agentKeysInputOf({ ...r, available: false, unavailable: "no Keychain" }, null)).not.toHaveProperty("warning");
+ });
+
it("calls the daemon's app methods through Tauri's agents_tool", async () => {
const calls: [string, Record<string, unknown> | undefined][] = [];
const ops = tauriAgentKeysOps(async <T,>(cmd: string, args?: Record<string, unknown>) => {
diff --git a/apps/cua-spaces-web/src/bridge/agent-keys.ts b/apps/cua-spaces-web/src/bridge/agent-keys.ts
index 6e467fb2ff..cfc4cfee4f 100644
--- a/apps/cua-spaces-web/src/bridge/agent-keys.ts
+++ b/apps/cua-spaces-web/src/bridge/agent-keys.ts
@@ -30,6 +30,8 @@ export interface AgentKeysInput {
/** Which credential each app that takes any provider uses, by app. */
uses?: Record<string, { provider: string; env: string; slot?: string }>;
unavailable?: string | null;
+ /** Keys are kept in an unencrypted file: shown as a notice while the buttons stay on. */
+ warning?: string | null;
error?: string | null;
}
@@ -104,6 +106,7 @@ export const agentKeysInputOf = (report: AgentKeysReport | undefined, error: Err
...((report?.keys ?? []).some((k) => k.slot) ? { extras: (report?.keys ?? []).filter((k) => k.slot).map(keyInput) } : {}),
...(report?.uses && Object.keys(report.uses).length ? { uses: report.uses } : {}),
unavailable: report?.available === false ? (report.unavailable ?? "this machine can't keep keys") : null,
+ ...(report?.available !== false && report?.insecure ? { warning: report.insecure } : {}),
error: error ? error.message : null,
});
@@ -291,6 +294,7 @@ export class AgentKeysStore {
providers: [],
available: !input.unavailable,
unavailable: input.unavailable ?? null,
+ ...(input.warning ? { insecure: input.warning } : {}),
};
this.set({ report, error: input.error ? new Error(input.error) : null, unsupported: false, sheet: open?.sheet ?? null, removing: open?.removing ?? null });
}
diff --git a/apps/cua-spaces-web/src/bridge/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.ts
index f9fafb6f5a..9cce1309c5 100644
--- a/apps/cua-spaces-web/src/bridge/connectors.ts
+++ b/apps/cua-spaces-web/src/bridge/connectors.ts
@@ -294,7 +294,7 @@ export function connectorsInputOf(
mcp: r.mcpConfig ? r.configured || /MCP/i.test(r.detail) : null,
mcpConfig: r.mcpConfig,
})),
- keys: { keys: keys.keys, unavailable: keys.unavailable, error: keys.error },
+ keys: { keys: keys.keys, unavailable: keys.unavailable, ...(keys.warning ? { warning: keys.warning } : {}), error: keys.error },
...(keys.extras?.length ? { keyExtras: keys.extras } : {}),
...(keys.uses && Object.keys(keys.uses).length ? { uses: keys.uses } : {}),
shellKeys: extra.shellKeys ?? [],
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index e8d77d1dbe..f581aaa161 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -270,6 +270,12 @@
"string",
"null"
]
+ },
+ "insecure": {
+ "type": [
+ "string",
+ "null"
+ ]
}
},
"required": [
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 7fee784fce..3ea3b3fab5 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -671,6 +671,7 @@ const AgentKeysShape = ref(
providers: list(object({ id: str, label: str, env: str })),
available: bool,
unavailable: nullable(str),
+ insecure: optNull(str),
}),
);
diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
index 035cd18535..39324ee94d 100644
--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
@@ -84,6 +84,8 @@ export interface AgentKeysReport {
available: boolean;
/** Why not, when they can't. */
unavailable: string | null;
+ /** Keys are kept in an unencrypted file (a Local development build without the Keychain). */
+ insecure?: string | null;
}
declare module "../protocol" {
@@ -212,6 +214,7 @@ export function agentKeysFromWire(raw: unknown): AgentKeysReport {
providers: providers.length ? providers : PROVIDERS,
available: o.available !== false,
unavailable: typeof o.unavailable === "string" && o.unavailable ? o.unavailable : null,
+ ...(typeof o.insecure === "string" && o.insecure ? { insecure: o.insecure } : {}),
};
}
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 22b29569b9..d8f2b96d8e 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -403,26 +403,39 @@ pub fn signed_by_cua() -> bool {
})
}
+/// Whether the default store is the OS vault, from the `CUA_CREDENTIAL_STORE`
+/// setting, the channel and whether this build is signed by Cua. Never on the
+/// Local channel (not even when the setting asks for it): see
+/// `CuaChannel::uses_login_keychain`.
+fn wants_vault(setting: &str, channel: cua_home::channel::CuaChannel, signed: bool) -> bool {
+ if !channel.uses_login_keychain() {
+ return false;
+ }
+ match setting {
+ "file" => false,
+ "keychain" | "keyring" => cfg!(any(target_os = "macos", target_os = "windows")),
+ _ => cfg!(target_os = "windows") || (cfg!(target_os = "macos") && signed),
+ }
+}
+
impl Store {
/// `CUA_CREDENTIAL_STORE` (`file` | `keychain`) or the default: the OS
/// vault on Windows and for Cua-signed macOS builds, else the file.
pub fn from_env() -> Self {
- let file = || Store::File(cua_home().join("credentials.json"));
let setting = std::env::var("CUA_CREDENTIAL_STORE").unwrap_or_default();
if let Some(dir) = setting.strip_prefix("test-keychain:") {
return Store::TestKeychain(PathBuf::from(dir));
}
- match setting.as_str() {
- "file" => file(),
+ let channel = cua_home::channel::CuaChannel::current();
+ #[cfg(target_os = "macos")]
+ let signed = signed_by_cua();
+ #[cfg(not(target_os = "macos"))]
+ let signed = false;
+ if wants_vault(&setting, channel, signed) {
#[cfg(any(target_os = "macos", target_os = "windows"))]
- "keychain" | "keyring" => Store::Keyring,
- #[cfg(target_os = "macos")]
- _ if signed_by_cua() => Store::Keyring,
- #[cfg(target_os = "windows")]
- _ => Store::Keyring,
- #[cfg(not(target_os = "windows"))]
- _ => file(),
+ return Store::Keyring;
}
+ Store::File(cua_home().join("credentials.json"))
}
/// `keychain` (the OS credential vault, or its test stand-in) or `file`.
@@ -860,6 +873,7 @@ impl Store {
std::env::var("CUA_CREDENTIAL_STORE").ok().as_deref(),
cua_home::is_test_process(),
cua_home::is_under_real_home(path),
+ cua_home::channel::CuaChannel::current(),
) && cfg!(target_os = "macos")
}
@@ -885,9 +899,12 @@ impl Store {
/// build (see [`Store::reads_vault_fallback`]). A refusal (the user
/// denied the keychain prompt) reads as nothing.
fn read_vault_fallback(&self, name: &str) -> Option<String> {
- if !self.reads_vault_fallback() {
- return None;
- }
+ vault_fallback_when(self.reads_vault_fallback(), || {
+ self.read_vault_fallback_now(name)
+ })
+ }
+
+ fn read_vault_fallback_now(&self, name: &str) -> Option<String> {
#[cfg(target_os = "macos")]
{
// A signed build that has not run since the service was renamed
@@ -1636,13 +1653,22 @@ fn vault_fallback_applies(
setting: Option<&str>,
test_process: bool,
under_real_home: bool,
+ channel: cua_home::channel::CuaChannel,
) -> bool {
- !test_process
+ // The Local channel never reads the login Keychain (see `wants_vault`).
+ channel.uses_login_keychain()
+ && !test_process
&& under_real_home
&& setting.is_none_or(|s| s.trim().is_empty())
&& path == default_path
}
+/// `read` (the vault) only when the fallback `applies`; else nothing, and the
+/// vault is never touched.
+fn vault_fallback_when(applies: bool, read: impl FnOnce() -> Option<String>) -> Option<String> {
+ if applies { read() } else { None }
+}
+
fn read_optional(path: &Path) -> Result<Option<String>> {
match std::fs::read_to_string(path) {
Ok(s) => Ok(Some(s)),
@@ -3079,23 +3105,70 @@ mod tests {
#[test]
fn only_the_default_file_store_outside_tests_reads_the_vault() {
let d = Path::new("/h/.cua/credentials.json");
- assert!(vault_fallback_applies(d, d, None, false, true));
- assert!(vault_fallback_applies(d, d, Some(" "), false, true));
- assert!(!vault_fallback_applies(d, d, Some("file"), false, true));
- assert!(!vault_fallback_applies(d, d, None, true, true));
+ use cua_home::channel::CuaChannel::{Local, Stable};
+ assert!(vault_fallback_applies(d, d, None, false, true, Stable));
+ assert!(vault_fallback_applies(d, d, Some(" "), false, true, Stable));
+ assert!(!vault_fallback_applies(
+ d,
+ d,
+ Some("file"),
+ false,
+ true,
+ Stable
+ ));
+ assert!(!vault_fallback_applies(d, d, None, true, true, Stable));
// A temporary CUA_HOME (a test harness, a sandbox) never does.
- assert!(!vault_fallback_applies(d, d, None, false, false));
+ assert!(!vault_fallback_applies(d, d, None, false, false, Stable));
assert!(!vault_fallback_applies(
Path::new("/elsewhere/credentials.json"),
d,
None,
false,
- true
+ true,
+ Stable
));
+ // The Local channel never reads the login Keychain, whatever else holds.
+ assert!(!vault_fallback_applies(d, d, None, false, true, Local));
// This test process never does.
assert!(!Store::File(cua_home().join("credentials.json")).reads_vault_fallback());
}
+ #[test]
+ fn local_never_touches_the_vault_and_stable_still_does() {
+ use cua_home::channel::CuaChannel::{Local, Stable};
+ // The Local store is the file whatever is asked, signed or not.
+ for setting in ["", "file", "keychain", "keyring"] {
+ for signed in [false, true] {
+ assert!(!wants_vault(setting, Local, signed), "{setting} {signed}");
+ }
+ }
+ // Stable is unchanged: an explicit vault, Cua-signed macOS, Windows.
+ assert!(!wants_vault("file", Stable, true));
+ assert_eq!(
+ wants_vault("keychain", Stable, false),
+ cfg!(any(target_os = "macos", target_os = "windows"))
+ );
+ assert_eq!(
+ wants_vault("", Stable, true),
+ cfg!(any(target_os = "macos", target_os = "windows"))
+ );
+ assert_eq!(wants_vault("", Stable, false), cfg!(target_os = "windows"));
+ // The vault's copy is not read when the fallback does not apply (Local),
+ // and is when it does (Stable's unsigned default store).
+ let d = Path::new("/h/.cua/credentials.json");
+ let touched = std::cell::Cell::new(false);
+ let read = || {
+ touched.set(true);
+ Some("secret".to_string())
+ };
+ let local = vault_fallback_applies(d, d, None, false, true, Local);
+ assert_eq!(vault_fallback_when(local, read), None);
+ assert!(!touched.get(), "the Local channel touched the vault");
+ let stable = vault_fallback_applies(d, d, None, false, true, Stable);
+ assert_eq!(vault_fallback_when(stable, read).as_deref(), Some("secret"));
+ assert!(touched.get());
+ }
+
#[test]
fn flows_parse() {
assert_eq!(Flow::parse("pkce").unwrap(), Flow::Browser);
diff --git a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs
index 8ea8152fd9..5fbf8d3df7 100644
--- a/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/agent_keys_cmd.rs
@@ -123,6 +123,9 @@ fn lines(report: &serde_json::Value) -> Vec<String> {
report["unavailable"].as_str().unwrap_or("no Keychain")
));
}
+ if let Some(w) = report["insecure"].as_str() {
+ v.push(format!("Warning: {w}."));
+ }
let keys = report["keys"].as_array().cloned().unwrap_or_default();
if keys.is_empty() {
v.push(crate::util::hint(
diff --git a/libs/cua/crates/cua-cli/src/connections_cmd.rs b/libs/cua/crates/cua-cli/src/connections_cmd.rs
index edb59a350e..958a3f1bf5 100644
--- a/libs/cua/crates/cua-cli/src/connections_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/connections_cmd.rs
@@ -329,6 +329,9 @@ pub fn list_lines(rows: &[Row], report: &serde_json::Value) -> Vec<String> {
report["unavailable"].as_str().unwrap_or("no Keychain")
));
}
+ if let Some(w) = report["insecure"].as_str() {
+ v.push(format!("Warning: {w}."));
+ }
let w = rows.iter().map(|r| r.id.len()).max().unwrap_or(0);
for r in rows {
let mut l = format!("{:<w$} {:<15}", r.id, state_words(r.state));
diff --git a/libs/cua/crates/cua-home/src/channel.rs b/libs/cua/crates/cua-home/src/channel.rs
index 2535ca3fa3..bc8376f0b3 100644
--- a/libs/cua/crates/cua-home/src/channel.rs
+++ b/libs/cua/crates/cua-home/src/channel.rs
@@ -260,6 +260,24 @@ impl CuaChannel {
self == Self::Local
}
+ /// Whether this channel may keep agent keys in an unencrypted 0600 file
+ /// when the OS vault is not available (an ad hoc signed development
+ /// build). Only the Local channel: Stable never saves a key to a file.
+ /// Every caller asks the channel, so no other code decides this.
+ pub fn allows_insecure_dev_store(self) -> bool {
+ matches!(self, Self::Local)
+ }
+
+ /// Whether this channel may read or write the user's login Keychain (the
+ /// OS credential vault) at run time. Not Local: an ad hoc signed build
+ /// is a new app to the Keychain on every rebuild, so each access would
+ /// ask the user again. Local keeps the session, the device key and the
+ /// Keyvault anchor in 0600 files under its home. Every caller asks the
+ /// channel, so no other code decides this.
+ pub fn uses_login_keychain(self) -> bool {
+ !self.allows_insecure_dev_store()
+ }
+
// ----- environment -----------------------------------------------------
/// The deployment when `CUA_ENV` is not set: Stable keeps
@@ -716,6 +734,21 @@ fn user_home() -> PathBuf {
#[cfg(test)]
mod tests {
+ #[test]
+ fn only_the_local_channel_may_keep_keys_in_a_file() {
+ for c in CuaChannel::ALL {
+ assert_eq!(
+ c.allows_insecure_dev_store(),
+ c == CuaChannel::Local,
+ "{c:?}"
+ );
+ }
+ assert!(CuaChannel::Stable.uses_login_keychain());
+ assert!(!CuaChannel::Local.uses_login_keychain());
+ assert!(!CuaChannel::Stable.allows_insecure_dev_store());
+ assert!(!CuaChannel::default().allows_insecure_dev_store());
+ }
+
use super::*;
fn paths(p: &[&str]) -> Vec<PathBuf> {
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/agent-keys.json b/libs/cua/crates/cua-spaces-app-core/parity/agent-keys.json
index ed646d81b9..6595f13978 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/agent-keys.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/agent-keys.json
@@ -1,6 +1,6 @@
{
"name": "agent-keys",
- "about": "Settings, Connections: the provider keys agents in your Spaces get. Anthropic and OpenAI always have a row (Not set until a key is saved; then its last four characters, when it was added, Replace and Remove); any other key has a row by its variable name. A build that can't keep keys, or a daemon that can't be read, says why instead of offering the buttons. Then the add or replace sheet for each kind of key (a new Other key asks for the variable and refuses names a shell or loader reads), the question before removing a key, and which variable names can hold a key.",
+ "about": "Settings, Connections: the provider keys agents in your Spaces get. Anthropic and OpenAI always have a row (Not set until a key is saved; then its last four characters, when it was added, Replace and Remove); any other key has a row by its variable name. A build that can't keep keys, or a daemon that can't be read, says why instead of offering the buttons; a Local development build that keeps keys in an unencrypted file warns about it and keeps the buttons. Then the add or replace sheet for each kind of key (a new Other key asks for the variable and refuses names a shell or loader reads), the question before removing a key, and which variable names can hold a key.",
"sections": [
{ "step": "nothing saved", "input": { "keys": [] } },
{
@@ -24,6 +24,13 @@
"unavailable": "this build of cua keeps credentials in a file, and agent keys are only kept in the Keychain (a Cua-signed build of Cua Spaces does). Set the key for the Cua daemon instead"
}
},
+ {
+ "step": "a development build keeps keys in an unencrypted file",
+ "input": {
+ "keys": [{ "provider": "anthropic", "env": "ANTHROPIC_API_KEY", "last4": "0000", "addedMs": 1790000000000 }],
+ "warning": "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets"
+ }
+ },
{ "step": "the daemon can't be read", "input": { "keys": [], "error": "The Cua daemon isn't running." } }
],
"saved": {
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/agent-keys.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/agent-keys.json
index 5cdfb09c12..9c380b35fe 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/agent-keys.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/agent-keys.json
@@ -62,6 +62,21 @@
},
"step": "this build can't keep keys"
},
+ {
+ "section": {
+ "addOther": "Add another key (For another provider, save its key under the variable its agent reads, like GEMINI_API_KEY.)",
+ "added": "Added",
+ "canEdit": true,
+ "intro": "Agents in your Spaces need a provider key to run. Keys stay on this Mac in the Keychain, and each one is only given to the agents that use it.",
+ "notice": "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets.",
+ "rows": [
+ "Anthropic | ANTHROPIC_API_KEY | anthropic | •••• 0000 | Replace | Remove | added 1790000000000 | For Claude Code and other agents that use Claude.",
+ "OpenAI | OPENAI_API_KEY | openai | Not set | Add key | - | added - | For Codex and other agents that use OpenAI models."
+ ],
+ "title": "Agent keys"
+ },
+ "step": "a development build keeps keys in an unencrypted file"
+ },
{
"section": {
"addOther": "Add another key (For another provider, save its key under the variable its agent reads, like GEMINI_API_KEY.)",
diff --git a/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs b/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
index aa6e4fd5c6..97ff7e7904 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
@@ -77,6 +77,10 @@ pub struct AgentKeysInput {
pub keys: Vec<AgentKeyInput>,
/// Why this machine can't keep keys (the daemon's words), when it can't.
pub unavailable: Option<String>,
+ /// Keys can be saved but only in an unencrypted file (a Local
+ /// development build without the Keychain): the daemon's warning, shown
+ /// in the notice while the buttons stay on.
+ pub warning: Option<String>,
/// The keys could not be read (no daemon, a refused Keychain).
pub error: Option<String>,
}
@@ -263,7 +267,7 @@ pub fn view_on(input: &AgentKeysInput, os: SpaceOs) -> AgentKeysView {
Some(k),
)
}));
- let notice = input
+ let blocked = input
.error
.as_ref()
.map(|e| format!("Couldn't read your agent keys: {e}"))
@@ -273,6 +277,8 @@ pub fn view_on(input: &AgentKeysInput, os: SpaceOs) -> AgentKeysView {
.as_ref()
.map(|why| format!("Keys can't be saved here: {why}."))
});
+ let can_edit = blocked.is_none();
+ let notice = blocked.or_else(|| input.warning.as_ref().map(|w| format!("{w}.")));
AgentKeysView {
title: "Agent keys".into(),
intro: intro(os),
@@ -281,7 +287,7 @@ pub fn view_on(input: &AgentKeysInput, os: SpaceOs) -> AgentKeysView {
other_help: "For another provider, save its key under the variable its agent reads, \
like GEMINI_API_KEY."
.into(),
- can_edit: notice.is_none(),
+ can_edit,
notice,
added_label: "Added".into(),
}
@@ -512,6 +518,24 @@ mod tests {
assert!(!v.can_edit && v.notice.unwrap().contains("no Keychain"));
}
+ #[test]
+ fn a_development_build_warns_that_keys_are_unencrypted_and_keeps_the_buttons_on() {
+ let warn = "Keychain not available in this development build: keys are stored unencrypted in ~/.cua-local/agent-keys. Do not use real production secrets";
+ let v = view(&AgentKeysInput {
+ warning: Some(warn.into()),
+ ..Default::default()
+ });
+ assert!(v.can_edit);
+ assert_eq!(v.notice.as_deref(), Some(format!("{warn}.").as_str()));
+ // A refusal still wins over the warning and turns the buttons off.
+ let v = view(&AgentKeysInput {
+ warning: Some(warn.into()),
+ unavailable: Some("no Keychain".into()),
+ ..Default::default()
+ });
+ assert!(!v.can_edit && v.notice.unwrap().starts_with("Keys can't be saved here"));
+ }
+
/// Where the keys stay is the shell's system's: the Mac's words are the
/// ones every build had before, to the byte.
#[test]
diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
index 36cb662379..ddb8acab5a 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
@@ -653,7 +653,13 @@ fn vault(os: SpaceOs) -> Option<&'static str> {
}
}
-fn notice(input: &ConnectorsInput) -> Option<String> {
+/// The warning shown beside working buttons (keys kept unencrypted).
+fn warning(input: &ConnectorsInput) -> Option<String> {
+ input.keys.warning.as_ref().map(|w| format!("{w}."))
+}
+
+/// What turns the buttons off, in words (credentials can't be read or saved).
+fn blocked(input: &ConnectorsInput) -> Option<String> {
input
.keys
.error
@@ -668,6 +674,11 @@ fn notice(input: &ConnectorsInput) -> Option<String> {
})
}
+/// The notice: why the buttons are off, else the unencrypted-keys warning.
+fn notice(input: &ConnectorsInput) -> Option<String> {
+ blocked(input).or_else(|| warning(input))
+}
+
fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {
let id = format!("app:{}", a.agent);
let busy = input.busy(&id);
@@ -909,7 +920,7 @@ pub fn view(input: &ConnectorsInput) -> ConnectorsView {
/// [`view`] in a shell on `os`.
pub fn view_on(input: &ConnectorsInput, os: SpaceOs) -> ConnectorsView {
let notice = notice(input);
- let can_edit = notice.is_none();
+ let can_edit = blocked(input).is_none();
// Every agent harness (installed here or not), then the other apps found here.
let apps: Vec<ConnectorAppRow> = HARNESS_APPS
.iter()
@@ -2308,7 +2319,7 @@ pub fn app_detail(input: &ConnectorsInput, agent: &str) -> Option<AppDetailView>
let row = app_row(input, a);
// An agent harness that is not on this machine has no local tools to switch.
let local = a.installed || a.configured;
- let can_edit = notice(input).is_none();
+ let can_edit = blocked(input).is_none();
let busy = input.busy(&format!("app:{agent}")).is_some();
let mut toggles = vec![];
if local {
@@ -3309,6 +3320,27 @@ mod tests {
assert!(v.providers.iter().all(|p| !p.button.enabled));
}
+ #[test]
+ fn the_unencrypted_keys_warning_shows_while_buttons_stay_on() {
+ let mut i = input();
+ i.keys.warning = Some("Keychain not available in this development build".into());
+ let v = view(&i);
+ assert!(v.can_edit);
+ assert_eq!(
+ v.notice.as_deref(),
+ Some("Keychain not available in this development build.")
+ );
+ assert!(v.providers.iter().any(|p| p.button.enabled));
+ i.keys.unavailable = Some("no Keychain".into());
+ let v = view(&i);
+ assert!(
+ !v.can_edit
+ && v.notice
+ .unwrap()
+ .starts_with("Sign-ins can't be saved here")
+ );
+ }
+
fn keyed(env: &str, provider: &str) -> AgentKeyInput {
let mut k = key(env, "abcd");
k.provider = provider.into();
diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/mod.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/mod.rs
index aa59b4c225..3f426ff540 100644
--- a/libs/cua/crates/cua-spaces-ext/src/daemon/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/mod.rs
@@ -292,7 +292,10 @@ fn build_keyvault(
// A debug daemon serving a test identity never touches the login
// keychain (passphrase-only vault, file generation anchor).
&& cfg!(any(target_os = "macos", target_os = "windows", target_os = "linux"))
- && !keyvault::test_identity_active();
+ && !keyvault::test_identity_active()
+ // The Local channel (an ad hoc signed build) never touches the login
+ // keychain: no OS protector, and the generation anchor is a file.
+ && cua_home::channel::CuaChannel::current().uses_login_keychain();
let presence = test_presence
.unwrap_or_else(|| Arc::new(keyvault::OsPresence) as Arc<dyn cua_keyvault::UserPresence>);
match keyvault::Keyvault::new(dir, backend, presence, os_protector) {
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 1d76f34581..20a6ee269a 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -6781,6 +6781,10 @@ pub struct AppAgentKeysInput {
pub keys: Vec<AppAgentKeyInput>,
/// Why this machine can't keep keys (the daemon's words), when it can't.
pub unavailable: Option<String>,
+ /// Keys can be saved but only in an unencrypted file (a Local
+ /// development build without the Keychain): the daemon's warning, shown
+ /// in the notice while the buttons stay on.
+ pub warning: Option<String>,
/// The keys could not be read (no daemon, a refused Keychain).
pub error: Option<String>,
}
diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rs
index c3dfcd4188..93cc206fdc 100644
--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs
+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs
@@ -337,6 +337,10 @@ pub struct KeysReport {
/// Why not, when they can't.
#[serde(skip_serializing_if = "Option::is_none")]
pub unavailable: Option<String>,
+ /// A warning, when keys can be saved but only in an unencrypted file
+ /// (a Local development build without the Keychain).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub insecure: Option<String>,
}
/// The credential an app was told to use: a variable and which of its saved
@@ -500,6 +504,8 @@ pub enum LoginSync {
pub struct AgentKeys {
store: Option<cua_auth::Store>,
unavailable: Option<String>,
+ // Set when the keys are kept in an unencrypted file ([`AgentKeys::new_for`]).
+ insecure: Option<String>,
// Serializes read-modify-write; holds the last read.
cache: Mutex<Option<(Instant, Vec<Stored>)>>,
// When Claude Code's own sign-in was last re-read ([`AgentKeys::sync_claude_login`]).
@@ -520,6 +526,26 @@ impl std::fmt::Debug for AgentKeys {
/// app shows it as "Keys can't be saved here: <this>."). A Mac's unsigned
/// build and Windows with `CUA_CREDENTIAL_STORE=file` have a vault they
/// could use; Linux has none.
+/// The warning shown while the Local channel keeps keys in a file: where, and
+/// that they are not encrypted.
+fn insecure_notice(credentials: &std::path::Path) -> String {
+ let file = credentials
+ .parent()
+ .map(|d| d.join(SECRET_NAME))
+ .unwrap_or_else(|| std::path::PathBuf::from(SECRET_NAME));
+ let shown = std::env::var_os("HOME")
+ .map(std::path::PathBuf::from)
+ .and_then(|h| {
+ file.strip_prefix(&h)
+ .ok()
+ .map(|r| format!("~/{}", r.display()))
+ })
+ .unwrap_or_else(|| file.display().to_string());
+ format!(
+ "Keychain not available in this development build: keys are stored unencrypted in {shown}. Do not use real production secrets"
+ )
+}
+
const fn file_store_reason() -> &'static str {
if cfg!(target_os = "macos") {
"this build of cua keeps credentials in a file, and agent keys are only kept in the Keychain (a Cua-signed build of Cua Spaces does). Set the key for the Cua daemon instead"
@@ -531,18 +557,36 @@ const fn file_store_reason() -> &'static str {
}
impl AgentKeys {
- /// Keys in `store`. A file store can't hold them (see the module docs).
+ /// Keys in `store` for this process's channel. A file store can't hold
+ /// them, except on the Local channel ([`AgentKeys::new_for`]).
pub fn new(store: cua_auth::Store) -> Self {
- if store.kind() == "keychain" {
- Self {
- store: Some(store),
- unavailable: None,
- cache: Mutex::new(None),
- claude_sync: Mutex::new(None),
- uses_cache: Mutex::new(None),
- }
+ Self::new_for(store, cua_home::channel::CuaChannel::current())
+ }
+
+ /// Keys in `store` for `channel`. A file store can't hold them (see the
+ /// module docs) unless `channel` allows the unencrypted development
+ /// store ([`cua_home::channel::CuaChannel::allows_insecure_dev_store`]: Local
+ /// only): then the keys are kept in a 0600 file beside the store's
+ /// credentials, and [`AgentKeys::insecure`] says so.
+ pub fn new_for(store: cua_auth::Store, channel: cua_home::channel::CuaChannel) -> Self {
+ let mut insecure = None;
+ let store = if store.kind() == "keychain" {
+ Some(store)
+ } else if let (true, cua_auth::Store::File(p)) =
+ (channel.allows_insecure_dev_store(), &store)
+ {
+ insecure = Some(insecure_notice(p));
+ Some(store)
} else {
- Self::unavailable(file_store_reason())
+ None
+ };
+ Self {
+ unavailable: store.is_none().then(|| file_store_reason().to_string()),
+ store,
+ insecure,
+ cache: Mutex::new(None),
+ claude_sync: Mutex::new(None),
+ uses_cache: Mutex::new(None),
}
}
@@ -551,12 +595,19 @@ impl AgentKeys {
Self {
store: None,
unavailable: Some(reason.into()),
+ insecure: None,
cache: Mutex::new(None),
claude_sync: Mutex::new(None),
uses_cache: Mutex::new(None),
}
}
+ /// The warning to show while keys are kept in an unencrypted file (a
+ /// Local development build without the Keychain); `None` otherwise.
+ pub fn insecure(&self) -> Option<&str> {
+ self.insecure.as_deref()
+ }
+
/// Whether keys can be saved.
pub fn available(&self) -> bool {
self.store.is_some()
@@ -636,6 +687,7 @@ impl AgentKeys {
providers: providers(),
available: self.available(),
unavailable: self.unavailable.clone(),
+ insecure: self.insecure.clone(),
})
}
@@ -2183,8 +2235,12 @@ mod tests {
#[test]
fn a_file_store_keeps_no_keys() {
let dir = std::env::temp_dir().join(format!("cua-agent-keys-file-{}", std::process::id()));
- let keys = AgentKeys::new(cua_auth::Store::File(dir.join("credentials.json")));
+ let keys = AgentKeys::new_for(
+ cua_auth::Store::File(dir.join("credentials.json")),
+ cua_home::channel::CuaChannel::Stable,
+ );
assert!(!keys.available());
+ assert!(keys.insecure().is_none());
let e = keys.set("anthropic", None, "sk-ant-test-0000").unwrap_err();
// The refusal names this system's vault, or says there is none (Linux).
let named = if cfg!(target_os = "macos") {
@@ -2203,6 +2259,76 @@ mod tests {
assert!(!r.available && r.unavailable.is_some() && r.keys.is_empty());
}
+ #[test]
+ fn the_local_channel_keeps_keys_in_a_private_file_and_says_so() {
+ let dir = std::env::temp_dir().join(format!("cua-agent-keys-local-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let keys = AgentKeys::new_for(
+ cua_auth::Store::File(dir.join("credentials.json")),
+ cua_home::channel::CuaChannel::Local,
+ );
+ assert!(keys.available());
+ let warning = keys.insecure().expect("a warning").to_string();
+ assert!(
+ warning.starts_with("Keychain not available in this development build"),
+ "{warning}"
+ );
+ assert!(
+ warning.contains("unencrypted") && warning.contains(SECRET_NAME),
+ "{warning}"
+ );
+ assert!(!warning.contains('\u{b7}'), "{warning}");
+ keys.set("anthropic", None, "sk-ant-test-0000").unwrap();
+ let file = dir.join(SECRET_NAME);
+ assert!(file.exists());
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+ // A new handle on the same file reads the key back, and the report says why to be careful.
+ let again = AgentKeys::new_for(
+ cua_auth::Store::File(dir.join("credentials.json")),
+ cua_home::channel::CuaChannel::Local,
+ );
+ let r = again.report().unwrap();
+ assert!(r.available && r.unavailable.is_none());
+ assert_eq!(r.insecure.as_deref(), Some(warning.as_str()));
+ assert_eq!(r.keys.len(), 1);
+ assert_eq!(r.keys[0].last4, "0000");
+ assert!(again.remove("ANTHROPIC_API_KEY").unwrap());
+ assert!(!file.exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn only_the_local_channel_can_save_to_a_file_and_the_vault_never_warns() {
+ let dir = std::env::temp_dir().join(format!("cua-agent-keys-chan-{}", std::process::id()));
+ let file = cua_auth::Store::File(dir.join("credentials.json"));
+ for c in cua_home::channel::CuaChannel::ALL {
+ let keys = AgentKeys::new_for(file.clone(), c);
+ assert_eq!(keys.available(), c.allows_insecure_dev_store(), "{c:?}");
+ assert_eq!(
+ keys.insecure().is_some(),
+ c.allows_insecure_dev_store(),
+ "{c:?}"
+ );
+ }
+ let stable = AgentKeys::new_for(file, cua_home::channel::CuaChannel::Stable);
+ assert!(stable.set("anthropic", None, "sk-ant-test-0000").is_err());
+ assert!(!dir.exists());
+ // The vault stand-in is a real vault: no warning on any channel.
+ let vault =
+ std::env::temp_dir().join(format!("cua-agent-keys-vault-{}", std::process::id()));
+ let keys = AgentKeys::new_for(
+ cua_auth::Store::TestKeychain(vault.clone()),
+ cua_home::channel::CuaChannel::Local,
+ );
+ assert!(keys.available() && keys.insecure().is_none());
+ let _ = std::fs::remove_dir_all(&vault);
+ }
+
#[test]
fn other_names_must_be_safe_env_names() {
for ok in ["MISTRAL_API_KEY", "groq_key", "_X", "A1"] {
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 7dd79b582a..3e49a7f051 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -4752,6 +4752,12 @@ public struct AppAgentKeysInput: Equatable, Hashable {
* Why this machine can't keep keys (the daemon's words), when it can't.
*/
public var unavailable: String?
+ /**
+ * Keys can be saved but only in an unencrypted file (a Local
+ * development build without the Keychain): the daemon's warning, shown
+ * in the notice while the buttons stay on.
+ */
+ public var warning: String?
/**
* The keys could not be read (no daemon, a refused Keychain).
*/
@@ -4766,11 +4772,17 @@ public struct AppAgentKeysInput: Equatable, Hashable {
/**
* Why this machine can't keep keys (the daemon's words), when it can't.
*/unavailable: String?,
+ /**
+ * Keys can be saved but only in an unencrypted file (a Local
+ * development build without the Keychain): the daemon's warning, shown
+ * in the notice while the buttons stay on.
+ */warning: String?,
/**
* The keys could not be read (no daemon, a refused Keychain).
*/error: String?) {
self.keys = keys
self.unavailable = unavailable
+ self.warning = warning
self.error = error
}
@@ -4792,6 +4804,7 @@ public struct FfiConverterTypeAppAgentKeysInput: FfiConverterRustBuffer {
try AppAgentKeysInput(
keys: FfiConverterSequenceTypeAppAgentKeyInput.read(from: &buf),
unavailable: FfiConverterOptionString.read(from: &buf),
+ warning: FfiConverterOptionString.read(from: &buf),
error: FfiConverterOptionString.read(from: &buf)
)
}
@@ -4799,6 +4812,7 @@ public struct FfiConverterTypeAppAgentKeysInput: FfiConverterRustBuffer {
public static func write(_ value: AppAgentKeysInput, into buf: inout [UInt8]) {
FfiConverterSequenceTypeAppAgentKeyInput.write(value.keys, into: &buf)
FfiConverterOptionString.write(value.unavailable, into: &buf)
+ FfiConverterOptionString.write(value.warning, into: &buf)
FfiConverterOptionString.write(value.error, into: &buf)
}
}