Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(host): stop throwaway hosts filling Keychain with keys
leepokaic33de6991df2
diff --git a/apps/desktop/e2e/credential-key.spec.ts b/apps/desktop/e2e/credential-key.spec.tsnew file mode 100644index 00000000..e67c37ce--- /dev/null+++ b/apps/desktop/e2e/credential-key.spec.ts@@ -0,0 +1,38 @@+import { test, expect } from '@playwright/test'+import { spawnSync } from 'node:child_process'+import { existsSync, statSync } from 'node:fs'+import { homedir } from 'node:os'+import { join } from 'node:path'+import { SANDBOX_PREFIX } from '../src/shared/dev-sandbox.ts'+import { attach, sandbox } from './sandbox.ts'++test('a sandbox keeps a saved sign-in under a key in its own folder and leaves Keychain alone', async () => {+ const { browser, page } = await attach()+ const site = `e2e-${Date.now()}.example.com`+ const { name } = sandbox()+ const row = page.getByText(site, { exact: true })+ try {+ await page.reload()+ await page.getByRole('button', { name: /Extensions/ }).click()+ await page.getByRole('button', { name: 'Credentials' }).click()+ await page.getByPlaceholder('github.com').fill(site)+ await page.getByPlaceholder('[email protected]').fill('e2e')+ await page.getByPlaceholder('Password or op:// reference').fill('e2e-not-a-secret')+ await page.getByRole('button', { name: 'Save sign-in' }).click()+ await expect(row).toBeVisible()++ const key = join(homedir(), SANDBOX_PREFIX + name, 'vault.key')+ expect(existsSync(key)).toBe(true)+ if (process.platform !== 'win32') expect(statSync(key).mode & 0o777).toBe(0o600)+ if (process.platform === 'darwin') {+ // Without -w, so this reads whether the item exists and never its secret.+ const item = spawnSync('security', ['find-generic-password', '-s', `Codync Dev (${name}) Safe Storage`])+ expect(item.status, 'the sandbox app left a Safe Storage item').not.toBe(0)+ }+ } finally {+ // Removes the sign-in again, so a sandbox's list doesn't grow with each run.+ await row.locator('xpath=ancestor::*[.//button[@title="Remove"]][1]').getByTitle('Remove').click().catch(() => {})+ await page.reload()+ await browser.close()+ }+})diff --git a/apps/desktop/src/main/environment.ts b/apps/desktop/src/main/environment.tsindex 5acecce6..06ba15d0 100644--- a/apps/desktop/src/main/environment.ts+++ b/apps/desktop/src/main/environment.ts@@ -24,4 +24,10 @@ if (identity.environment === 'dev') {const sandbox = app.isPackaged ? undefined : process.env.CODYNC_HOMEapp.setName(sandbox ? sandboxLabel(identity.name, sandbox) : identity.name)app.setPath('userData', sandbox ? join(sandbox, 'desktop') : join(app.getPath('appData'), identity.name))+ // A sandbox leaves no Safe Storage item in the system's credential store: Keychain (first switch), a Linux keyring+ // (second); Windows keeps its key in the sandbox. Its sealed files then protect nothing, like its host's key.+ if (sandbox) {+ app.commandLine.appendSwitch('use-mock-keychain')+ app.commandLine.appendSwitch('password-store', 'basic')+ }}diff --git a/apps/desktop/tools/dev.mjs b/apps/desktop/tools/dev.mjsindex 64321c67..284c747e 100644--- a/apps/desktop/tools/dev.mjs+++ b/apps/desktop/tools/dev.mjs@@ -171,7 +171,8 @@ async function sandbox() {const host = buildHost()const log = join(home, 'host.log')- const hostEnv = { ...childEnv(), CODYNC_HOME: home, ...(flags.cloud ? {} : { CODYNC_CLOUD: 'off' }) }+ // CODYNC_VAULT: the credential key goes with the sandbox folder, so Keychain neither keeps it nor asks about it.+ const hostEnv = { ...childEnv(), CODYNC_HOME: home, CODYNC_VAULT: 'folder', ...(flags.cloud ? {} : { CODYNC_CLOUD: 'off' }) }const out = openSync(log, 'a')const hostProcess = spawn(host, ['serve', '--port', String(port)], { env: hostEnv, stdio: ['ignore', out, out] })hostProcess.on('error', (e) => fail(`Couldn't start ${host}: ${e.message}`))diff --git a/apps/desktop/tools/native-host.mjs b/apps/desktop/tools/native-host.mjsindex f2c53a43..2be0bf45 100644--- a/apps/desktop/tools/native-host.mjs+++ b/apps/desktop/tools/native-host.mjs@@ -27,6 +27,15 @@ const profile = process.env.CODYNC_HOST_PROFILE ?? (env === 'dev' ? 'dev-app' :if (!['dev-app', 'release'].includes(profile)) throw new Error(`unknown host profile ${profile}`)const build = (target) => run(cargo, ['build', '--profile', profile, '--manifest-path', join(host, 'Cargo.toml'), '--target', target])const built = (target, name) => join(host, 'target', target, profile, name)+// Keychain trusts a certificate across rebuilds, but an ad hoc signature only for that one build. A Mac without+// this certificate keeps the ad hoc signature, and Codync Dev's host asks for its key again after each rebuild.+const signDevHost = (file) => {+ try {+ execFileSync('codesign', ['--force', '--timestamp=none', '--identifier', 'codync-host', '--sign', 'Apple Development: Pokai Lee (6KFK5J2LB4)', file], { stdio: 'pipe', timeout: 60_000 })+ } catch (e) {+ console.log(`host: keeping the ad hoc signature (${String(e.stderr ?? e.message).trim()})`)+ }+}mkdirSync(out, { recursive: true })if (process.platform === 'win32') {const target = process.arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc'@@ -39,5 +48,6 @@ if (process.platform === 'win32') {const targets = env === 'dev' ? [native] : ['aarch64-apple-darwin', 'x86_64-apple-darwin']for (const target of targets) build(target)run('lipo', ['-create', '-output', join(out, 'codync-host'), ...targets.map((t) => built(t, 'codync-host'))])+ if (env === 'dev') signDevHost(join(out, 'codync-host'))}console.log(`host: ${env}`)diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex 887ed23b..9ad24a59 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -171,8 +171,9 @@ helper at the top of `electron-builder.yml` doesn't depend on the environment; p(the release workflow, `.github/workflows/release-desktop.yml`, shows how).`dist:mac:dev` signs with the team 7FUM8A8H72 development certificate (`CSC_NAME` in`package.json`): the Screen launch agent only runs code from that team, and the keychain holds-another team's certificate electron-builder would otherwise pick. Update the name when it is-renewed.+another team's certificate electron-builder would otherwise pick. When it is renewed, update the+name there and in `signDevHost` (`tools/native-host.mjs`), which otherwise falls back to an ad hoc+signature and Keychain asks after every rebuild again.Codync and Codync Dev can run side by side: separate app identities, host services, ports, data and login callbacks. See [Dev app isolation](../guides/dev-app.md) for the resource map and external signing/account setup.For a local signed Mac build, explicitly select a development identity from the project'sdiff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.mdindex 229ed344..cf0ead28 100644--- a/docs/features/connector-credentials.md+++ b/docs/features/connector-credentials.md@@ -19,6 +19,9 @@ its selected host.- Headless Linux: provide a session D-Bus and unlocked Secret Service for theservice user. An unavailable keyring gives an actionable error. There is noplaintext, kernel-keyring-only or automatic ephemeral fallback.+- Disposable hosts only (tests and [worktree sandboxes](../guides/dev-app.md#worktree-sandboxes)): a Dev build+ with `CODYNC_VAULT=folder` keeps the key in `<data dir>/vault.key`, protected by file permissions alone.+ A production build ignores the switch.Unlocking runs on a blocking worker, one read at a time; callers that arrivemeanwhile share its outcome. A locked Linux keyring gets one unlock prompt thatdiff --git a/docs/guides/cloudflare-testing.md b/docs/guides/cloudflare-testing.mdindex cdcfc7b4..de82ba63 100644--- a/docs/guides/cloudflare-testing.md+++ b/docs/guides/cloudflare-testing.md@@ -62,7 +62,7 @@ cd cloud && npx wrangler d1 migrations apply codync-local --env local --localcurl -s https://sunny-mollusk-8651.clerk.accounts.dev/.well-known/jwks.json # → CLERK_JWT_KEY as PEMnpx wrangler dev --env local --port 8787 --var CLERK_ISSUER:https://sunny-mollusk-8651.clerk.accounts.dev \--var "CLERK_JWT_KEY:$PEM" --var "DEVICE_CERT_KEY:$JWK" # a throwaway Ed25519 JWK-CODYNC_HOME=$TMP CODYNC_CLOUD_URL=http://127.0.0.1:8787 CODYNC_DEVICE_CERT_KEY=$PUB codync-host serve --port 19391+CODYNC_HOME=$TMP CODYNC_VAULT=folder CODYNC_CLOUD_URL=http://127.0.0.1:8787 CODYNC_DEVICE_CERT_KEY=$PUB codync-host serve --port 19391```- iPhone: launch with `SIMCTL_CHILD_CODYNC_CLOUD_URL=http://127.0.0.1:8787` (also while running `npm run phone-account`).diff --git a/docs/guides/dev-app.md b/docs/guides/dev-app.mdindex 801e3218..701d6b57 100644--- a/docs/guides/dev-app.md+++ b/docs/guides/dev-app.md@@ -26,6 +26,7 @@ Xcode configurations separate environment from optimization: `Debug` and `Releas- Host data in `~/.codync-dev-<worktree folder>`, which also holds the app's session, account and single-instance lock (`desktop/`). The window and menu bar read `Codync Dev (<name>)`.- A port from 19300–19399, picked free on the first run and kept in that folder's `sandbox.json`, so a paired simulator stays paired.- A host built from the worktree's own code (`node tools/native-host.mjs dev`; on Linux `cargo build`, honoring `CARGO_TARGET_DIR`; or `CODYNC_HOST_BIN`), started and stopped with the app, logging to `host.log`. No launchd/systemd service, and the dev cloud is off.+- Nothing in the system's credential store, so a sandbox never prompts and leaves nothing behind when its folder goes. The host runs with `CODYNC_VAULT=folder` (its key is `vault.key` beside the data; production builds ignore the switch, and end-to-end test hosts use it too) and the app with Chromium's `use-mock-keychain` (macOS) and `password-store=basic` (Linux; Windows keeps its key in the sandbox). Only file permissions protect these, so keep real tokens out of a sandbox and test them on the default Codync Dev. A sandbox made before this switch, or given a copy of a host's database, keeps using that Keychain key while it exists, so a copied database's secrets stay readable; deleting it or `--prune` leaves any item of its own in Keychain, and nothing cleans it up. On its first start after the switch, its app signs in again (on its own with a test account) and gets a new device key.- The run prints the commands that pair a phone or simulator (`codync-host pair`), create the sandbox's iPhone simulator and open the terminal UI against the sandbox.Flags go after `npm run dev --`: `--shared` takes the default Codync Dev from a worktree (quit the main checkout's first); `--sandbox` runs a sandbox from the main checkout, for a second session on `dev`; `--name <name>` runs the sandbox of that name, for another copy of the same checkout; `--cloud` lets the sandbox host use the dev cloud (each sandbox then shows as another computer); `--cdp` opens the DevTools protocol on the sandbox port + 10000; `--list` shows every sandbox; `--prune` deletes the ones whose worktree is gone (and their Clerk test accounts and iPhone simulators), so run it after removing worktrees.@@ -70,6 +71,9 @@ Secrets for running the project locally live in git-ignored env files at the mai| Windows Run key value | `CodyncHost` | `CodyncDevHost` || Windows supervisor | `codync-hostw.exe` | `codync-dev-hostw.exe` || macOS Screen helper identifier | `com.pokai.Codync.screen` | `com.pokai.Codync.dev.screen` |+| Host credential key (Keychain / Secret Service service) | `dev.codync.credentials` | `dev.codync.development.credentials` |++On macOS, `native-host.mjs dev` signs the host with the Apple Development certificate when this Mac has it, so Keychain keeps trusting Codync Dev's host across rebuilds. After the first signed build it asks one last time for an existing key: choose **Always Allow**. Without the certificate the host stays ad hoc signed, and Keychain asks again after each rebuild.The iPhone extensions inherit the parent environment. Electron Dev stores its browser session, account credentials and SSH profiles under its own `Codync Dev` user-data directory. SSH host-key storage and orphan-tunnel cleanup are also separate. Dev never installs production updates and does not rewrite the shared Claude Code status line.diff --git a/docs/guides/test-stack.md b/docs/guides/test-stack.mdindex ed758311..40434258 100644--- a/docs/guides/test-stack.md+++ b/docs/guides/test-stack.md@@ -4,7 +4,7 @@ How the end-to-end (e2e) checks drive the apps: Playwright for the desktop app,## Host tests-`host/tests` drive real hosts against fake agents (the Python scripts in `tests/fixtures`). `tests/common` starts every test host with `CODYNC_AGENT_CHECKS=off`, as do `cloud/test/e2e/relay.e2e.ts` and `tools/check-connectors.py`, so it never runs the computer's agent CLIs for their sign-in and usage checks and never touches your logins. A test of those checks turns them back on (`tests/agent_checks_e2e.rs`).+`host/tests` drive real hosts against fake agents (the Python scripts in `tests/fixtures`). `tests/common` starts every test host with `CODYNC_AGENT_CHECKS=off`, as do `cloud/test/e2e/relay.e2e.ts` and `tools/check-connectors.py`, so it never runs the computer's agent CLIs for their sign-in and usage checks and never touches your logins. A test of those checks turns them back on (`tests/agent_checks_e2e.rs`). `tests/common` also sets `CODYNC_VAULT=folder`, so a test's credential key stays out of the system's credential store and goes with its data; `tools/check-connectors.py` keeps a real Keychain key on purpose.Run them one at a time: never start a test binary several times in parallel, or several copies of the suite, not even to hunt a flake. Repeat it one run after another, a few times at most. On 2026-11-04 parallel repeats left about 200 `claude -p /usage` processes behind, using 55 GB on a 32 GB Mac, and froze it.diff --git a/host/src/agent/new_bot.rs b/host/src/agent/new_bot.rsindex 95b97ef3..78fc4225 100644--- a/host/src/agent/new_bot.rs+++ b/host/src/agent/new_bot.rs@@ -13,18 +13,8 @@ pub async fn with_defaults(hub: &Arc<Hub>, mut b: Value) -> Result<BotConfig> {// A lead is made by the host or picked by the user (`chat::lead`), never on creation.b["lead"] = false.into();// Connectors are on for a new bot unless the client picked them.- // Without a credential store (headless Linux) no connector can run, so the bot starts with none.if b["connectors"].is_null() && b["kind"] != "group" {- b["connectors"] = match market::vault::unlock(hub.clone()).await {- Ok(()) => json!(market::connector_ids(&hub.store)?),- Err(e) => {- tracing::warn!(- error = format!("{e:#}"),- "credential store unavailable; new bot starts without connectors"- );- json!([])- }- };+ b["connectors"] = default_connectors(hub).await?;}// Skills too: every installed one is on unless the client picked them, but a bot's skill stays with that bot.if b["skills"].is_null() && b["kind"] != "group" {@@ -42,6 +32,22 @@ pub async fn with_defaults(hub: &Arc<Hub>, mut b: Value) -> Result<BotConfig> {serde_json::from_value(b).context("invalid bot")}+/// Every connector a new bot gets. With none saved the credential store stays shut, which is what keeps the+/// lead bot of a new computer from opening it at start-up.+async fn default_connectors(hub: &Arc<Hub>) -> Result<Value> {+ if !market::connectors_saved(&hub.store)? {+ return Ok(json!([]));+ }+ // Without a credential store (headless Linux) no connector can run, so the bot starts with none.+ Ok(match market::vault::unlock(hub.clone()).await {+ Ok(()) => json!(market::connector_ids(&hub.store)?),+ Err(e) => {+ tracing::warn!(error = format!("{e:#}"), "credential store unavailable; new bot starts without connectors");+ json!([])+ }+ })+}+/// A new bot's agent (`agents` as `backends::list` gives them): Claude when it runs here, else the/// first one Codync knows that does. A registry agent nobody chose is never the default.fn default_backend(agents: &[Value]) -> &str {diff --git a/host/src/market/composio.rs b/host/src/market/composio.rsindex 6e2246dd..fe201cb8 100644--- a/host/src/market/composio.rs+++ b/host/src/market/composio.rs@@ -19,7 +19,7 @@ const API: &str = "https://backend.composio.dev/api/v3.1";const TIMEOUT: Duration = Duration::from_secs(30);/// Connector ids for Composio apps: `composio-<toolkit slug>`.pub const PREFIX: &str = "composio-";-const SLOT: &str = "composio";+pub(super) const SLOT: &str = "composio";pub const KEY_URL: &str = "https://platform.composio.dev";pub const INSTRUCTIONS: &str = "Act in the user's connected apps through Composio. Find a tool with \diff --git a/host/src/market/mod.rs b/host/src/market/mod.rsindex 20166a23..6b944cdd 100644--- a/host/src/market/mod.rs+++ b/host/src/market/mod.rs@@ -181,14 +181,22 @@ fn load<T: for<'de> Deserialize<'de>>(store: &crate::store::Store, key: &str) ->store.kv_get(key).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()}+const CONNECTORS_SLOT: &str = "connectors";+pub fn connectors(store: &crate::store::Store) -> Result<Vec<Connector>> {- vault::read(store, "connectors")?.map_or_else(|| Ok(Vec::new()), |s| serde_json::from_str(&s).map_err(Into::into))+ vault::read(store, CONNECTORS_SLOT)?+ .map_or_else(|| Ok(Vec::new()), |s| serde_json::from_str(&s).map_err(Into::into))}pub fn skills(store: &crate::store::Store) -> Vec<Skill> {load(store, "skills")}+/// Whether a connector or connected app was ever saved, answered without the vault.+pub fn connectors_saved(store: &crate::store::Store) -> Result<bool> {+ Ok(store.kv_read(CONNECTORS_SLOT)?.is_some() || store.kv_read(composio::SLOT)?.is_some())+}+/// Everything a bot can turn on: installed connectors and connected apps.pub fn connector_ids(store: &crate::store::Store) -> Result<Vec<String>> {Ok(list_connectors(store)?["items"]@@ -262,7 +270,7 @@ fn save<T: Serialize>(store: &crate::store::Store, key: &str, items: &[T]) -> Re}pub fn save_connectors(store: &crate::store::Store, items: &[Connector]) -> Result<()> {- vault::write(store, "connectors", &serde_json::to_string(items)?)+ vault::write(store, CONNECTORS_SLOT, &serde_json::to_string(items)?)}/// Serialize read/modify/write so OAuth refreshes and installations cannot replace each other.@@ -365,6 +373,35 @@ mod tests {assert_eq!(c.public()["canSignIn"], true, "set up with a token: can switch to signing in");}+ /// The credential store stays shut until something was saved, and a new bot still gets all of it after that.+ #[tokio::test]+ async fn a_new_bot_gets_what_the_computer_saved() {+ let dir = std::env::temp_dir().join(format!("codync-new-bot-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).expect("temp dir");+ let app = json!({"id": "1", "toolkit": "slack", "name": "Slack", "status": "active"});+ for (slot, saved, id) in [+ (CONNECTORS_SLOT, json!([{"id": "linear", "name": "Linear", "url": "https://example.com/mcp"}]), "linear"),+ (composio::SLOT, json!({"key": "k", "userId": "u", "connections": [app]}), "composio-slack"),+ ] {+ let store = crate::store::Store::open(std::path::Path::new(":memory:")).expect("memory store");+ let hub = crate::hub::Hub::new(+ store,+ "test".into(),+ crate::remote::identity::Identity::load_or_create(&dir).expect("identity"),+ "test".into(),+ 19222,+ );+ let new_bot = async || {+ let asked = json!({"name": "n", "backend": "fixture", "command": "true", "cwd": dir});+ crate::agent::new_bot::with_defaults(&hub, asked).await.expect("new bot").connectors+ };+ assert!(new_bot().await.is_empty(), "nothing saved yet");+ vault::write(&hub.store, slot, &saved.to_string()).expect("save");+ assert_eq!(new_bot().await, [id], "{slot}");+ }+ let _ = std::fs::remove_dir_all(dir);+ }+#[tokio::test]async fn new_installs_turn_on_for_every_bot() {let dir = std::env::temp_dir().join(format!("codync-connectors-{}", uuid::Uuid::new_v4()));diff --git a/host/src/market/vault.rs b/host/src/market/vault.rsindex 3680b102..8734763a 100644--- a/host/src/market/vault.rs+++ b/host/src/market/vault.rs@@ -1,7 +1,8 @@//! Encrypted records backed by the operating system credential store. The database-//! contains ciphertext only; its random master key lives in Keychain/Secret Service.-use crate::{LockExt, store::Store};-use anyhow::{Result, anyhow, bail};+//! contains ciphertext only; its random master key lives in Keychain/Secret Service+//! (a disposable host: in a file beside its data, see `key_in_folder`).+use crate::{LockExt, environment::Environment, store::Store};+use anyhow::{Context, Result, anyhow, bail};use base64::{Engine, engine::general_purpose::STANDARD};use chacha20poly1305::{XChaCha20Poly1305, XNonce,@@ -11,9 +12,9 @@ use std::{sync::Arc, time::Duration};use zeroize::Zeroizing;const PREFIX: &str = "vault:v1:";-const SERVICE: &str = match crate::environment::Environment::current() {- crate::environment::Environment::Main => "dev.codync.credentials",- crate::environment::Environment::Dev => "dev.codync.development.credentials",+const SERVICE: &str = match Environment::current() {+ Environment::Main => "dev.codync.credentials",+ Environment::Dev => "dev.codync.development.credentials",};/// How long an unlock prompt (Keychain, Secret Service) may wait for an answer.@@ -46,6 +47,48 @@ pub async fn unlock(hub: Arc<crate::hub::Hub>) -> Result<()> {}fn read_key(store: &Store) -> Result<Zeroizing<Vec<u8>>> {+ let path = crate::service::data_dir().join("vault.key");+ let in_folder = key_in_folder(+ Environment::current(),+ std::env::var("CODYNC_VAULT").ok().as_deref(),+ path.try_exists()?,+ store.kv_read("vault.initialized")?.is_some(),+ );+ let key = if in_folder { folder_key(&path)? } else { keyring_key(store)? };+ if key.len() != 32 {+ bail!("Invalid credential key.");+ }+ store.kv_set("vault.initialized", "true")?;+ Ok(Zeroizing::new(key))+}++/// `CODYNC_VAULT=folder`, for data that gets thrown away (tests, worktree sandboxes): the key sits beside the+/// data and goes with it, and the credential store never hears of this host. Only file permissions protect+/// it, so a production build ignores the switch. Data already sealed with a credential store key stays there:+/// it is initialized with no key file (a sandbox from before the switch, or one given a copy of a host's database).+fn key_in_folder(env: Environment, switch: Option<&str>, file_exists: bool, initialized: bool) -> bool {+ env == Environment::Dev && switch == Some("folder") && (file_exists || !initialized)+}++fn folder_key(path: &std::path::Path) -> Result<Vec<u8>> {+ match std::fs::read(path) {+ Ok(key) => Ok(key),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ let key = new_key()?;+ crate::remote::identity::write_private(path, &key)?;+ Ok(key)+ }+ Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),+ }+}++fn new_key() -> Result<Vec<u8>> {+ let mut key = vec![0; 32];+ getrandom::fill(&mut key).map_err(|_| anyhow!("Could not generate credential key"))?;+ Ok(key)+}++fn keyring_key(store: &Store) -> Result<Vec<u8>> {let id = if let Some(id) = store.kv_read("vault.id")? {id} else {@@ -56,26 +99,20 @@ fn read_key(store: &Store) -> Result<Zeroizing<Vec<u8>>> {#[cfg(target_os = "linux")]unlock_secret_service().map_err(|_| unavailable())?;let entry = keyring::Entry::new(SERVICE, &id).map_err(|_| unavailable())?;- let key = match entry.get_secret() {- Ok(key) => key,+ match entry.get_secret() {+ Ok(key) => Ok(key),Err(keyring::Error::NoEntry) => {if store.kv_read("vault.initialized")?.is_some() {bail!("The credential key is missing. Restore this computer's keychain; encrypted credentials were preserved.");}- let mut key = vec![0; 32];- getrandom::fill(&mut key).map_err(|_| anyhow!("Could not generate credential key"))?;+ let key = new_key()?;entry.set_secret(&key).map_err(|_| unavailable())?;- key+ Ok(key)}- Err(_) => return Err(unavailable()),- };- if key.len() != 32 {- bail!("Invalid credential key; restore this computer's keychain.");+ Err(_) => Err(unavailable()),}- store.kv_set("vault.initialized", "true")?;- Ok(Zeroizing::new(key))}/// keyring keeps its item in the default collection and prompts to unlock it with no@@ -138,6 +175,21 @@ pub fn write(store: &Store, slot: &str, value: &str) -> Result<()> {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn only_a_dev_host_that_asks_keeps_its_key_in_a_file() {+ use Environment::{Dev, Main};+ let folder = Some("folder");+ assert!(key_in_folder(Dev, folder, false, false), "a new host makes one");+ assert!(key_in_folder(Dev, folder, true, true), "and keeps it");+ assert!(!key_in_folder(Dev, folder, false, true), "data from before the switch stays on its keyring key");+ assert!(!key_in_folder(Main, folder, false, false), "production ignores the switch");+ assert!(!key_in_folder(Main, folder, true, true), "even with a key file there");+ assert!(!key_in_folder(Dev, None, false, false), "off without the switch");+ assert!(!key_in_folder(Dev, None, true, true), "whatever file is there");+ assert!(!key_in_folder(Dev, Some("keyring"), false, false), "or with another value");+ }+#[test]#[ignore = "requires an unlocked OS keychain or Secret Service session"]fn platform_keyring_roundtrip() {diff --git a/host/src/remote/identity.rs b/host/src/remote/identity.rsindex 2351315c..fad9ecdb 100644--- a/host/src/remote/identity.rs+++ b/host/src/remote/identity.rs@@ -115,7 +115,7 @@ impl Identity {}/// Creates `path` readable by this user only, before any secret is written to it.-fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {+pub(crate) fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {use std::io::Write as _;let mut opts = std::fs::OpenOptions::new();opts.write(true).create(true).truncate(true);diff --git a/host/tests/agent_checks_e2e.rs b/host/tests/agent_checks_e2e.rsindex 0dc61856..37977b70 100644--- a/host/tests/agent_checks_e2e.rs+++ b/host/tests/agent_checks_e2e.rs@@ -82,9 +82,7 @@ async fn a_test_host_never_runs_the_agent_clis() {let response = call(&base, &home, method).send().await.unwrap();let status = response.status();let body = response.text().await.unwrap();- // `agentAuth` opens the vault first: a computer with no keyring, like Linux CI, refuses it there, before any agent.- let no_keyring = method == "agentAuth" && body.contains("Secure credential storage");- assert!(status.is_success() || no_keyring, "{method}: {status} {body}");+ assert!(status.is_success(), "{method}: {status} {body}");}tokio::time::sleep(Duration::from_secs(1)).await;assert_eq!(std::fs::read_to_string(&log).unwrap_or_default(), "");diff --git a/host/tests/common/mod.rs b/host/tests/common/mod.rsindex aaa45bc5..1d00d445 100644--- a/host/tests/common/mod.rs+++ b/host/tests/common/mod.rs@@ -40,6 +40,8 @@ pub async fn serve_with(home: &Path, env: &[(&str, &std::ffi::OsStr)]) -> (Child.env("CODYNC_DEVICE_CERT_KEY", test_cloud_key())// A test host leaves the computer's agent CLIs and the user's logins alone..env("CODYNC_AGENT_CHECKS", "off")+ // And the computer's credential store: its key goes with `home`, so no test can leave one behind.+ .env("CODYNC_VAULT", "folder").envs(env.iter().copied()).stdout(Stdio::null()).stderr(std::fs::File::create(&log).map_or_else(|_| Stdio::null(), Stdio::from))diff --git a/host/tests/vault_e2e.rs b/host/tests/vault_e2e.rsnew file mode 100644index 00000000..11b960ef--- /dev/null+++ b/host/tests/vault_e2e.rs@@ -0,0 +1,41 @@+//! When a host makes its credential key, and where a disposable host keeps it (`market::vault`).++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use serde_json::json;+use std::time::Duration;++/// The rule behind every other test staying out of the credential store: nothing opens it before a secret exists.+#[tokio::test]+async fn a_new_computer_makes_no_key_until_a_secret_is_saved() {+ let host = Host::start().await;+ common::eventually("the host made its lead bot", Duration::from_secs(30), async || {+ host.snapshot().await["bots"].as_array().unwrap().iter().any(|b| b["lead"] == true)+ })+ .await;+ let bot = host.call("createBot", json!({"name": "Plain", "backend": "custom", "command": "unused"})).await;+ assert_eq!(bot["bot"]["connectors"], json!([]));+ assert!(!host.home.join("vault.key").exists(), "a host with nothing saved opened its vault");++ host.call("credentialSaveLogin", json!({"site": "example.com", "username": "me", "password": "pw"})).await;+ assert!(host.home.join("vault.key").exists());+}++#[tokio::test]+async fn a_folder_key_outlives_a_restart_and_only_its_user_can_read_it() {+ let mut host = Host::start().await;+ host.call("credentialSaveLogin", json!({"site": "example.com", "username": "me", "password": "pw"})).await;+ let key = host.home.join("vault.key");+ assert_eq!(std::fs::read(&key).unwrap().len(), 32);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt as _;+ assert_eq!(std::fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600);+ }+ host.restart(|_| {}).await;+ let logins = host.call("credentialLogins", json!({})).await;+ assert_eq!(logins["items"][0]["username"], "me", "{logins}");+}