diff --git a/AGENTS.md b/AGENTS.md index 1f08936..e9ce432 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,11 +75,13 @@ port → output.** | Module | Role | Port(s) → shim | | ---------------- | ------------------------------------------------------------------------------------------------ | -------------- | +| `sha256.rs` | A dependency-free SHA-256 (`hex_digest`). Exists only because Claude Code namespaces its Keychain service with `sha256($CLAUDE_CONFIG_DIR)[0..8]`, and the dependency budget does not stretch to `sha2` + six transitive crates for one 8-char string. Checked against the FIPS vectors. | — | +| `claude_env.rs` | `ClaudeEnv` — resolves everything Claude Code's own env vars move: the config dir, `.claude.json`, the credential-fallback dir, and the **Keychain service name**. See *Config directories* below. | — | | `model.rs` | Domain types: `Account` (uuid/org/email/org-name) and `Profile` (persisted `account.json`). | — | | `error.rs` | `Error` / `Result` (`ProfileNotFound`, `ReservedName`, `Invalid`, wrapped `Io`/`Json`). | — | | `config.rs` | Read/splice `~/.claude.json`: extract + reinsert the `{oauthAccount, userID}` identity, leaving every other key untouched. Plain-file JSON, temp-tested. | — | -| `creds.rs` | `CredentialStore` trait + the `FileStore` (`/.credentials.json`) fallback used off macOS. Temp-tested. | `CredentialStore` | -| `creds_shim.rs` | Real macOS Keychain adapter (`security` binary) + `platform_store` `cfg` selection. | `CredentialStore` → **shim** | +| `creds.rs` | `CredentialStore` + `Keychain` traits, the `FileStore` (`/.credentials.json`), and `KeychainStore` — the composite that mirrors Claude Code's own Keychain-over-plaintext arbitration (see *Headless machines* below). Also `security` exit-code classification, `acct` parsing, and `Backend`/`select_store`. Temp-tested against a fake `Keychain`. | `CredentialStore`, `Keychain` | +| `creds_shim.rs` | `SecurityBinary` — a single `run(args, stdin)` that spawns `security` and returns unclassified exit status + streams — plus `platform_store` (`cfg` + env, no decisions). | `Keychain` → **shim** | | `store.rs` | The on-disk profile store under `$CCSWITCH_HOME`; `TokenScope` (`PerAccount` / `PerAccountOrg`) — the knob behind the auth-loss fix. Temp-tested. | — | | `switch.rs` | `Switcher` — save/activate orchestration over `creds` + `config` + `store`; re-snapshots the outgoing credential into every token-sharing sibling. | consumes `CredentialStore` | | `cli.rs` | clap types, the `Command` model, `App::dispatch` + every handler, `System` port, path resolution, symlink planning, `search`/`isolate`/`seed` logic, completion generation. | `System` | @@ -111,6 +113,65 @@ Preserve this behavior; it is the reason the Rust tool exists. --- +## Headless machines (why the credential store is a composite) + +Claude Code's macOS credential store is `keychain-with-plaintext-fallback`: it +reads the Keychain first and falls back to `~/.claude/.credentials.json`, and a +failed Keychain write migrates the credential into that file. Over SSH the +login Keychain cannot be unlocked without a GUI prompt (`security` exits 36, +`errSecInteractionNotAllowed`), so Claude Code is living entirely in the file. + +A Keychain-only `ccswitch` is blind to that: `read` sees nothing (so `save` +claims you are signed out and `sync_current` silently drops a rotated token) +and `write` cannot land the incoming credential, leaving `~/.claude.json` +naming the new account while the live token is still the old one — which Claude +Code reports as not logged in. + +`KeychainStore` therefore mirrors the same arbitration, and in particular keeps +**one** authoritative copy: a successful Keychain write deletes the plaintext +file, and a failed one deletes the Keychain item. Dropping either half of that +lets a stale copy shadow the switch from the other kind of session. Preserve +this; `$CCSWITCH_CREDENTIALS=file` forces the plaintext path outright. + +Note that `security find-generic-password -g` prints attributes on **stdout** +and the password on stderr — parsing the wrong stream silently yields no `acct` +attribute forever. + +The credential must never reach `security`'s argv, which `ps` exposes to every +user on the machine. `KeychainStore::store_password` hex-encodes it and pipes +`add-generic-password … -X ` to `security -i`, dropping to argv only past +the 4032-character stdin limit — the same boundary Claude Code uses. The +`Keychain` port is deliberately a single `run(args, stdin)` so that this choice +is a decision in `creds.rs` with a test asserting the secret never appears in +argv, not something buried in the shim. + +--- + +## Config directories (why `claude_env.rs` exists) + +`$CLAUDE_CONFIG_DIR` moves `.claude.json` and the credential fallback, and it +**renames the Keychain item**: Claude Code appends +`-${sha256(dir).hex[0..8]}` to the service name. A tool that hardcodes +`"Claude Code-credentials"` therefore reads and writes a *different account's* +credential whenever the variable is set — including inside `ccswitch isolate`, +which launches `claude` with it set to the isolate directory. + +`ClaudeEnv` owns that computation; `cli_shim::run` reads the variables and +everything else takes resolved paths and a service `String`. Two relatives feed +the same derivation: `$CLAUDE_SECURESTORAGE_CONFIG_DIR` (relocates only the +credential store, and "defined but empty" means the *default* store, not a new +namespace) and `$CLAUDE_CODE_CUSTOM_OAUTH_URL` (a `-custom-oauth` infix on both +the config file name and the service). + +Profile and isolate roots hang off the resolved config dir too, so +`cli::ccswitch_home`/`isolate_home` take that directory, not `$HOME`. + +Claude Code NFC-normalizes the directory before hashing; we hash the bytes as +given, which agrees for any already-NFC path. Documented, not fixed — NFC would +mean a Unicode dependency. + +--- + ## Adding a feature 1. **Decide where the logic goes.** Any real side effect (a new process to diff --git a/CHANGELOG.md b/CHANGELOG.md index fc70d7d..394ef94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,59 @@ All notable changes to ccswitch are documented here. The format follows ## [Unreleased] -_Nothing yet._ +### Fixed + +- **Switching now works on headless and pure-SSH machines.** Claude Code's macOS + credential store is a composite — Keychain first, falling back to plaintext + `~/.claude/.credentials.json`, with a failed Keychain write migrating the + credential into that file. Over SSH the login Keychain cannot be unlocked + without a GUI prompt (`security` exits 36, `errSecInteractionNotAllowed`), so + Claude Code lives entirely in the file. `ccswitch` only ever looked at the + Keychain, so `save` reported "no active credential" on a machine that was + signed in, `sync_current` silently dropped rotated tokens, and a switch left + `~/.claude.json` naming the new account while the live token still belonged to + the old one — which Claude Code reports as **not logged in**. The macOS store + now mirrors Claude Code's arbitration and keeps exactly one authoritative + copy: a successful Keychain write deletes the plaintext file, a failed one + deletes the Keychain item, so a stale copy can never shadow the switch from + the other kind of session. +- **The Keychain `acct` attribute is captured again.** `security + find-generic-password -g` prints attributes on stdout and the password on + stderr; `account_attr` parsed stderr, so it always came back empty and every + profile stored `keychain_account: ""`. (Writes fell through to `$USER`, which + is what Claude Code looks items up by, so this was invisible.) + +- **`$CLAUDE_CONFIG_DIR` is honored.** It moves `.claude.json` and the + credential fallback, and — the part that is easy to miss — it *renames the + Keychain item*: Claude Code namespaces the service with the first eight hex + characters of `sha256($CLAUDE_CONFIG_DIR)`. `ccswitch` hardcoded + `"Claude Code-credentials"`, so with the variable set it read and wrote a + **different account's** credential while patching the wrong config file. This + affected ordinary use, because `ccswitch isolate` launches `claude` with + `CLAUDE_CONFIG_DIR` set to the isolate directory. The related + `$CLAUDE_SECURESTORAGE_CONFIG_DIR` and `$CLAUDE_CODE_CUSTOM_OAUTH_URL` feed + the same derivation and are honored too. +- **The OAuth token no longer appears in `security`'s argv**, where `ps` exposed + it to every user on the machine for the duration of a switch. It is now + hex-encoded and piped to `security -i`, with the same argv fallback Claude + Code uses for a blob past the stdin limit. Account attributes are also + sanitized the way Claude Code sanitizes them, so the two cannot end up + addressing different items. + +### Changed + +- Profile and isolate storage now default to `accounts/` and `profiles/` inside + Claude Code's **resolved** config directory rather than always `~/.claude`. + With `$CLAUDE_CONFIG_DIR` unset this is the same path as before. With it set, + each config directory gets its own profiles; set `$CCSWITCH_HOME` to a fixed + path to share one set across all of them. + +### Added + +- `$CCSWITCH_CREDENTIALS=file` (or `plaintext`) forces the plaintext backend and + skips the Keychain entirely — for a Mac you only ever reach over SSH. +- `ccswitch save` now says when the Keychain is locked or unreachable, instead + of reporting a reachable-but-empty store and a locked one identically. ## [0.1.3] — 2026-07-16 diff --git a/README.md b/README.md index 05578c3..bcf43ff 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ orgs — and jump straight into a session.** `ccswitch` is a small, fast, cross-shell command-line tool. An account is two things that must travel together: the OAuth credential (in the macOS Keychain, -or `~/.claude/.credentials.json` elsewhere) and the identity Claude Code +falling back to `~/.claude/.credentials.json`) and the identity Claude Code validates it against (`oauthAccount` + `userID` inside `~/.claude.json`). `ccswitch` snapshots both into a plain profile directory and restores them as a unit, so one command becomes an account and drops you into `claude`. @@ -119,8 +119,19 @@ Profile names may not collide with a reserved subcommand word (`save`, `add`, | Variable | Purpose | Default | | --- | --- | --- | -| `CCSWITCH_HOME` | Where saved profiles live. | `~/.claude/accounts` | -| `CCSWITCH_ISOLATE_HOME` | Where isolated profiles + shared memory live. | `~/.claude/profiles` | +| `CCSWITCH_HOME` | Where saved profiles live. | `accounts/` inside Claude Code's config dir | +| `CCSWITCH_ISOLATE_HOME` | Where isolated profiles + shared memory live. | `profiles/` inside Claude Code's config dir | +| `CCSWITCH_CREDENTIALS` | Credential backend. `file` (or `plaintext`) skips the macOS Keychain and uses the plaintext fallback only. | auto | + +`ccswitch` also *reads* Claude Code's own variables so it always addresses the +same account Claude Code would — see [Multiple config +directories](#multiple-config-directories). + +| Variable | Effect | +| --- | --- | +| `CLAUDE_CONFIG_DIR` | Moves `.claude.json`, the credential fallback, and the Keychain item. | +| `CLAUDE_SECURESTORAGE_CONFIG_DIR` | Moves only the credential store. | +| `CLAUDE_CODE_CUSTOM_OAUTH_URL` | Adds a `-custom-oauth` infix to both. | --- @@ -297,10 +308,42 @@ prints a hint. --- +## Multiple config directories + +`$CLAUDE_CONFIG_DIR` does not merely move `~/.claude`. It also moves +`.claude.json`, and — the part that is easy to miss — it **renames the Keychain +item**: Claude Code namespaces the service with the first eight hex characters +of the directory's SHA-256. + +```text +unset → "Claude Code-credentials" +CLAUDE_CONFIG_DIR=/w → "Claude Code-credentials-" +``` + +So a tool that ignores the variable does not just read the wrong config file — +it reads and writes a *different account's* credential. `ccswitch` computes the +same service name, so every command addresses exactly the account Claude Code +would in the same environment. + +This is not an exotic case: `ccswitch isolate` launches `claude` with +`CLAUDE_CONFIG_DIR` set to the isolate directory, so any `ccswitch` run from +inside an isolated session is affected. + +Profile and isolate storage follow the config directory too, so a given +`$CLAUDE_CONFIG_DIR` gets its own set of profiles. Point `$CCSWITCH_HOME` at a +fixed path if you would rather share one set across all of them. + +> Claude Code normalizes the directory to Unicode NFC before hashing. +> `ccswitch` hashes the path as given, which agrees for every ASCII path and in +> practice everything short of a decomposed non-ASCII path. If you have one, +> set `CCSWITCH_CREDENTIALS=file` or use an ASCII path. + +--- + ## Profile storage -Profiles live in `$CCSWITCH_HOME` (default `~/.claude/accounts`), one directory -per profile: +Profiles live in `$CCSWITCH_HOME` (default `accounts/` inside Claude Code's +config directory, i.e. `~/.claude/accounts`), one directory per profile: ``` ~/.claude/accounts/work/ @@ -320,6 +363,49 @@ git or a cloud folder, **encrypt it** — use a private repo with [SOPS](https://github.com/getsops/sops), or a real secret manager. Never commit plaintext tokens to a shared or public repo. +On macOS the token is hex-encoded and piped to `security -i` rather than passed +as a command-line argument, so it is not visible in `ps` to other users on the +machine while a switch runs. (A blob too large for `security`'s stdin limit +falls back to argv, exactly as Claude Code does.) + +--- + +## Headless and SSH machines + +Claude Code does not keep its credential in the macOS Keychain unconditionally. +Its store is a composite: it reads the Keychain first and falls back to +plaintext `~/.claude/.credentials.json`, and when a Keychain write fails it +moves the credential into that file instead. On a Mac you only ever reach over +SSH, the login Keychain cannot be unlocked without a GUI prompt — `security` +exits 36, `errSecInteractionNotAllowed` — so Claude Code is living entirely in +the plaintext file. Linux and Windows always use the file. + +`ccswitch` mirrors that arbitration exactly, so the two never disagree about +which copy is authoritative: + +- **Reading** — the Keychain wins. If it is empty *or* unreachable, the file is + read, so `ccswitch save` on a headless box snapshots the credential Claude + Code is actually using instead of reporting you as signed out. +- **Writing** — the Keychain is tried first and, on success, the plaintext file + is deleted: left in place it is a stale credential waiting to resurface the + next time the Keychain is unreachable. If the Keychain write fails, the file + is written and the Keychain item dropped, so a stale Keychain copy cannot + shadow the switch from a GUI session. + +Without this, a switch over SSH left `~/.claude.json` naming the account you +switched *to* while the live token still belonged to the account you switched +*from* — which Claude Code reports as not logged in. + +If every `security` call on a machine is a dead end anyway, set +`CCSWITCH_CREDENTIALS=file` to skip the Keychain entirely. + +> On a Mac used **both** at the console and over SSH, expect the credential to +> migrate to the plaintext file the first time you switch over SSH, and to +> return to the Keychain the first time you switch at the console. That is +> Claude Code's own behavior; `ccswitch` keeps exactly one authoritative copy +> either way. `~/.claude/.credentials.json` is written `0600`, but it is a +> bearer token in plaintext — the same trade Claude Code makes. + --- ## Notes diff --git a/legacy-fish/functions/ccswitch.fish b/legacy-fish/functions/ccswitch.fish index 4548923..77e4386 100644 --- a/legacy-fish/functions/ccswitch.fish +++ b/legacy-fish/functions/ccswitch.fish @@ -1,6 +1,6 @@ function ccswitch -d "switch between multiple Claude Code accounts" set -l home (__ccswitch_home) - set -l config "$HOME/.claude.json" + set -l config (__ccswitch_config_file) set -l cmd $argv[1] switch "$cmd" @@ -41,41 +41,105 @@ function __ccswitch_home -d "resolve the profile store directory" if set -q CCSWITCH_HOME echo $CCSWITCH_HOME else - echo "$HOME/.claude/accounts" + echo (__ccswitch_claude_dir)"/accounts" + end +end + +# Claude Code's state follows $CLAUDE_CONFIG_DIR: the config file, the +# plaintext credential fallback, and — easy to miss — the *name of the Keychain +# item*, which it namespaces with the first 8 hex chars of the directory's +# SHA-256. Ignore the variable and you read another account's credential. +# ccswitch isolate launches claude with CLAUDE_CONFIG_DIR set, so this matters +# for any ccswitch run from inside an isolated session. +function __ccswitch_claude_dir -d "Claude Code's config directory" + if set -q CLAUDE_CONFIG_DIR; and test -n "$CLAUDE_CONFIG_DIR" + echo "$CLAUDE_CONFIG_DIR" + else + echo "$HOME/.claude" + end +end + +function __ccswitch_config_file -d "path of Claude Code's global .claude.json" + if set -q CLAUDE_CONFIG_DIR; and test -n "$CLAUDE_CONFIG_DIR" + echo "$CLAUDE_CONFIG_DIR/.claude.json" + else + echo "$HOME/.claude.json" + end +end + +function __ccswitch_service -d "Keychain service name for the active config dir" + if set -q CLAUDE_CONFIG_DIR; and test -n "$CLAUDE_CONFIG_DIR" + set -l hash (printf '%s' "$CLAUDE_CONFIG_DIR" | shasum -a 256 | cut -c1-8) + echo "Claude Code-credentials-$hash" + else + echo "Claude Code-credentials" end end function __ccswitch_cred_read -d "print the current Claude Code OAuth credential blob" - switch (uname) - case Darwin - security find-generic-password -s "Claude Code-credentials" -w 2>/dev/null - case '*' - if test -f "$HOME/.claude/.credentials.json" - cat "$HOME/.claude/.credentials.json" - else - return 1 - end + # Claude Code's macOS store is a composite: it reads the Keychain first and + # falls back to the plaintext file. Over SSH the login Keychain cannot be + # unlocked without a GUI prompt (security exits 36), so the file is where + # the credential actually lives — look there too, or we report a signed-in + # machine as signed out. + set -l file (__ccswitch_claude_dir)"/.credentials.json" + if test (uname) = Darwin + and security find-generic-password -s (__ccswitch_service) -w 2>/dev/null + return 0 + end + if test -f "$file" + cat "$file" + else + return 1 end end function __ccswitch_cred_acct -d "print the keychain account attribute (macOS only)" - security find-generic-password -s "Claude Code-credentials" -g 2>&1 \ + security find-generic-password -s (__ccswitch_service) -g 2>&1 \ | string replace -rf '^.*"acct"="(.*)"$' '$1' end function __ccswitch_cred_write -d "write an OAuth credential blob into the platform store" set -l blob $argv[1] set -l acct $argv[2] - switch (uname) - case Darwin - test -z "$acct"; and set acct "$USER" - security delete-generic-password -s "Claude Code-credentials" >/dev/null 2>&1 - security add-generic-password -U -a "$acct" -s "Claude Code-credentials" -w "$blob" - case '*' - mkdir -p "$HOME/.claude" - printf '%s' "$blob" >"$HOME/.claude/.credentials.json" - chmod 600 "$HOME/.claude/.credentials.json" + set -l dir (__ccswitch_claude_dir) + set -l file "$dir/.credentials.json" + if test (uname) = Darwin + set -l svc (__ccswitch_service) + test -z "$acct"; and set acct "$USER" + # Claude Code substitutes a fixed name for anything outside this set, + # so we must too or we address a different item. + if not string match -qr '^[a-zA-Z0-9._-]+$' -- "$acct" + set acct claude-code-user + end + # An item is keyed by (service, account); adding under a new account + # attribute would leave a second one behind. Clear first. + security delete-generic-password -s "$svc" >/dev/null 2>&1 + # Pass the token hex-encoded down stdin rather than on argv: argv is + # visible to every user on the box via `ps`. Claude Code does the same, + # dropping to argv only when the command outgrows the stdin limit. + set -l hex (printf '%s' "$blob" | xxd -p | tr -d '\n') + set -l script (printf 'add-generic-password -U -a "%s" -s "%s" -X "%s"' "$acct" "$svc" "$hex") + set -l ok 1 + if test (string length -- "$script") -le 4031 + printf '%s\n' "$script" | security -i 2>/dev/null; and set ok 0 + else + security add-generic-password -U -a "$acct" -s "$svc" -X "$hex" 2>/dev/null; and set ok 0 + end + if test $ok -eq 0 + # The Keychain wins every read, so a leftover plaintext file is a + # stale credential waiting to be picked up the next time the + # Keychain is unreachable. + rm -f "$file" + return 0 + end + # No usable Keychain (SSH / headless). Fall through to the plaintext + # file Claude Code itself falls back to; the item is already deleted, + # so no stale Keychain copy can shadow us from a GUI session. end + mkdir -p "$dir" + printf '%s' "$blob" >"$file" + chmod 600 "$file" end function __ccswitch_save -d "snapshot the current account into a profile" @@ -299,7 +363,7 @@ function __ccswitch_isolate_home -d "resolve the isolated-profile base directory if set -q CCSWITCH_ISOLATE_HOME echo $CCSWITCH_ISOLATE_HOME else - echo "$HOME/.claude/profiles" + echo (__ccswitch_claude_dir)"/profiles" end end @@ -383,7 +447,7 @@ function __ccswitch_seed -d "sync the shared isolate memory/history from ~/.clau set -l base (__ccswitch_isolate_home) set -l shared "$base/shared" set -l src $argv[1] - test -z "$src"; and set src "$HOME/.claude" + test -z "$src"; and set src (__ccswitch_claude_dir) if not test -d "$src" echo "ccswitch: source '$src' not found" >&2 diff --git a/src/claude_env.rs b/src/claude_env.rs new file mode 100644 index 0000000..1fb2df7 --- /dev/null +++ b/src/claude_env.rs @@ -0,0 +1,256 @@ +//! Where Claude Code keeps its state, as a function of the environment. +//! +//! `$CLAUDE_CONFIG_DIR` does not merely move `~/.claude`: it also moves +//! `.claude.json`, and — the part that is easy to miss — it *renames the +//! Keychain item*. Claude Code namespaces the service by appending the first +//! eight hex characters of `sha256($CLAUDE_CONFIG_DIR)`: +//! +//! ```text +//! unset → "Claude Code-credentials" +//! /Users/x/.work → "Claude Code-credentials-744b5d0e" +//! ``` +//! +//! So a `ccswitch` that ignores the variable does not just read the wrong +//! config file — it reads and writes a *different account's* Keychain item. +//! That matters in ordinary use, because `ccswitch isolate` launches `claude` +//! with `CLAUDE_CONFIG_DIR` set to the isolate directory; running `ccswitch` +//! from inside such a session used to swap the main account's credential. +//! +//! Two related variables come along for the ride, because they feed the same +//! computation: `$CLAUDE_SECURESTORAGE_CONFIG_DIR` relocates only the +//! credential store, and `$CLAUDE_CODE_CUSTOM_OAUTH_URL` gives the config file +//! and the Keychain service a `-custom-oauth` infix. +//! +//! ## Normalization +//! +//! Claude Code normalizes the directory to Unicode NFC before hashing. +//! `ccswitch` hashes the bytes as given, which agrees for any path already in +//! NFC — every ASCII path, and in practice everything short of a +//! decomposed-form path typed on macOS. A decomposed non-ASCII +//! `$CLAUDE_CONFIG_DIR` would hash differently; set `$CCSWITCH_CREDENTIALS` to +//! `file` there, or use an ASCII path. + +use crate::sha256; +use std::path::{Path, PathBuf}; + +/// The Claude Code environment variables that move its state around. +/// +/// Each field holds the raw variable: `None` when unset. An empty string is +/// treated as unset for [`ClaudeEnv::config_dir`], but is meaningful for +/// `secure_storage_dir`, where Claude Code reads "defined but empty" as an +/// explicit request for the default store. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ClaudeEnv { + /// `$CLAUDE_CONFIG_DIR`. + pub config_dir: Option, + /// `$CLAUDE_SECURESTORAGE_CONFIG_DIR`. + pub secure_storage_dir: Option, + /// `$CLAUDE_CODE_CUSTOM_OAUTH_URL`, reduced to whether it is set. + pub custom_oauth: bool, +} + +/// The base Keychain service name and the infix for a custom OAuth endpoint. +const SERVICE_STEM: &str = "Claude Code"; +const SERVICE_LEAF: &str = "-credentials"; +const CUSTOM_OAUTH_SUFFIX: &str = "-custom-oauth"; + +impl ClaudeEnv { + /// Build from already-read variables, treating empty strings as unset + /// except where Claude Code gives them meaning. + #[must_use] + pub fn new( + config_dir: Option, + secure_storage_dir: Option, + custom_oauth_url: Option, + ) -> Self { + Self { + config_dir: config_dir.filter(|v| !v.is_empty()), + secure_storage_dir, + custom_oauth: custom_oauth_url.is_some_and(|v| !v.is_empty()), + } + } + + /// The infix that a custom OAuth endpoint adds to the config file name and + /// the Keychain service. + #[must_use] + pub fn oauth_suffix(&self) -> &'static str { + if self.custom_oauth { + CUSTOM_OAUTH_SUFFIX + } else { + "" + } + } + + /// Claude Code's configuration directory: `$CLAUDE_CONFIG_DIR`, else + /// `~/.claude`. This is the directory holding `projects/`, `plugins/`, and + /// the plaintext credential fallback. + #[must_use] + pub fn config_dir(&self, home: &Path) -> PathBuf { + self.config_dir + .as_ref() + .map_or_else(|| home.join(".claude"), PathBuf::from) + } + + /// The global config file Claude Code validates the credential against. + /// + /// Note it sits *beside* the config directory by default (`~/.claude.json`, + /// not `~/.claude/.claude.json`), but *inside* `$CLAUDE_CONFIG_DIR` when + /// that is set. + #[must_use] + pub fn config_path(&self, home: &Path) -> PathBuf { + let base = self + .config_dir + .as_ref() + .map_or_else(|| home.to_path_buf(), PathBuf::from); + base.join(format!(".claude{}.json", self.oauth_suffix())) + } + + /// The directory holding the plaintext `.credentials.json` fallback: + /// `$CLAUDE_SECURESTORAGE_CONFIG_DIR` when set to a non-empty value, + /// `~/.claude` when it is set but empty, else [`ClaudeEnv::config_dir`]. + #[must_use] + pub fn credentials_dir(&self, home: &Path) -> PathBuf { + match self.secure_storage_dir.as_deref() { + Some("") => home.join(".claude"), + Some(dir) => PathBuf::from(dir), + None => self.config_dir(home), + } + } + + /// The Keychain service name the credential is stored under. + /// + /// The default store is unsuffixed; any relocation namespaces it by the + /// first eight hex characters of the directory's SHA-256. + #[must_use] + pub fn keychain_service(&self) -> String { + let scope = match self.secure_storage_dir.as_deref() { + // Defined but empty means "the default store", not a new namespace. + Some("") => None, + Some(dir) => Some(dir), + None => self.config_dir.as_deref(), + }; + let suffix = scope.map_or_else(String::new, |dir| { + format!("-{}", &sha256::hex_digest(dir.as_bytes())[..8]) + }); + format!( + "{SERVICE_STEM}{}{SERVICE_LEAF}{suffix}", + self.oauth_suffix() + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn home() -> PathBuf { + PathBuf::from("/Users/someone") + } + + fn env(config_dir: Option<&str>) -> ClaudeEnv { + ClaudeEnv::new(config_dir.map(str::to_string), None, None) + } + + #[test] + fn defaults_match_a_plain_install() { + let e = env(None); + assert_eq!( + e.config_dir(&home()), + PathBuf::from("/Users/someone/.claude") + ); + // Beside the directory, not inside it. + assert_eq!( + e.config_path(&home()), + PathBuf::from("/Users/someone/.claude.json") + ); + assert_eq!( + e.credentials_dir(&home()), + PathBuf::from("/Users/someone/.claude") + ); + assert_eq!(e.keychain_service(), "Claude Code-credentials"); + assert_eq!(e.oauth_suffix(), ""); + } + + #[test] + fn config_dir_moves_everything_including_the_keychain_item() { + let e = env(Some("/Users/someone/.claude-work")); + assert_eq!( + e.config_dir(&home()), + PathBuf::from("/Users/someone/.claude-work") + ); + // The config file moves *inside* the directory here. + assert_eq!( + e.config_path(&home()), + PathBuf::from("/Users/someone/.claude-work/.claude.json") + ); + assert_eq!( + e.credentials_dir(&home()), + PathBuf::from("/Users/someone/.claude-work") + ); + let expected = format!( + "Claude Code-credentials-{}", + &sha256::hex_digest(b"/Users/someone/.claude-work")[..8] + ); + assert_eq!(e.keychain_service(), expected); + // And it is genuinely a different item from the default one. + assert_ne!(e.keychain_service(), env(None).keychain_service()); + } + + #[test] + fn empty_config_dir_is_treated_as_unset() { + let e = env(Some("")); + assert_eq!( + e.config_dir(&home()), + PathBuf::from("/Users/someone/.claude") + ); + assert_eq!(e.keychain_service(), "Claude Code-credentials"); + } + + #[test] + fn secure_storage_dir_moves_only_the_credential_store() { + let e = ClaudeEnv::new(Some("/cfg".to_string()), Some("/secure".to_string()), None); + // Config still follows CLAUDE_CONFIG_DIR... + assert_eq!(e.config_path(&home()), PathBuf::from("/cfg/.claude.json")); + // ...while the credential store follows the storage variable. + assert_eq!(e.credentials_dir(&home()), PathBuf::from("/secure")); + let expected = format!( + "Claude Code-credentials-{}", + &sha256::hex_digest(b"/secure")[..8] + ); + assert_eq!(e.keychain_service(), expected); + } + + #[test] + fn secure_storage_dir_set_but_empty_selects_the_default_store() { + // Claude Code reads "defined but empty" as an explicit opt-out of the + // namespacing that CLAUDE_CONFIG_DIR would otherwise apply. + let e = ClaudeEnv::new(Some("/cfg".to_string()), Some(String::new()), None); + assert_eq!( + e.credentials_dir(&home()), + PathBuf::from("/Users/someone/.claude") + ); + assert_eq!(e.keychain_service(), "Claude Code-credentials"); + } + + #[test] + fn custom_oauth_url_infixes_the_config_file_and_the_service() { + let e = ClaudeEnv::new(None, None, Some("https://example.test/oauth".to_string())); + assert_eq!(e.oauth_suffix(), "-custom-oauth"); + assert_eq!( + e.config_path(&home()), + PathBuf::from("/Users/someone/.claude-custom-oauth.json") + ); + assert_eq!(e.keychain_service(), "Claude Code-custom-oauth-credentials"); + // Empty means unset. + let e = ClaudeEnv::new(None, None, Some(String::new())); + assert_eq!(e.oauth_suffix(), ""); + } + + #[test] + fn is_debuggable_and_comparable() { + let e = env(Some("/x")); + assert_eq!(e.clone(), e); + assert_ne!(ClaudeEnv::default(), e); + assert!(format!("{e:?}").contains("ClaudeEnv")); + } +} diff --git a/src/cli.rs b/src/cli.rs index 9e83246..3abf03f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -314,26 +314,15 @@ pub struct Paths { /// Resolve the profile-store root: `$CCSWITCH_HOME` or `~/.claude/accounts`. #[must_use] -pub fn ccswitch_home(var: Option, home: &Path) -> PathBuf { - non_empty(var).map_or_else(|| home.join(".claude").join("accounts"), PathBuf::from) +pub fn ccswitch_home(var: Option, claude_dir: &Path) -> PathBuf { + non_empty(var).map_or_else(|| claude_dir.join("accounts"), PathBuf::from) } -/// Resolve the isolate base: `$CCSWITCH_ISOLATE_HOME` or `~/.claude/profiles`. +/// Resolve the isolate base: `$CCSWITCH_ISOLATE_HOME`, else `profiles/` inside +/// Claude Code's config directory (`~/.claude`, or `$CLAUDE_CONFIG_DIR`). #[must_use] -pub fn isolate_home(var: Option, home: &Path) -> PathBuf { - non_empty(var).map_or_else(|| home.join(".claude").join("profiles"), PathBuf::from) -} - -/// The `~/.claude.json` config path for a home directory. -#[must_use] -pub fn config_path(home: &Path) -> PathBuf { - home.join(".claude.json") -} - -/// The `~/.claude` directory for a home directory. -#[must_use] -pub fn claude_dir(home: &Path) -> PathBuf { - home.join(".claude") +pub fn isolate_home(var: Option, claude_dir: &Path) -> PathBuf { + non_empty(var).map_or_else(|| claude_dir.join("profiles"), PathBuf::from) } /// Treat an empty string the same as an unset variable. @@ -1077,27 +1066,36 @@ mod tests { fn path_resolution_prefers_env_then_defaults() { let home = Path::new("/home/u"); assert_eq!( - ccswitch_home(None, home), + ccswitch_home(None, &home.join(".claude")), PathBuf::from("/home/u/.claude/accounts") ); assert_eq!( - ccswitch_home(Some(String::new()), home), + ccswitch_home(Some(String::new()), &home.join(".claude")), PathBuf::from("/home/u/.claude/accounts") ); assert_eq!( - ccswitch_home(Some("/custom".to_string()), home), + ccswitch_home(Some("/custom".to_string()), &home.join(".claude")), PathBuf::from("/custom") ); assert_eq!( - isolate_home(None, home), + isolate_home(None, &home.join(".claude")), PathBuf::from("/home/u/.claude/profiles") ); assert_eq!( - isolate_home(Some("/iso".to_string()), home), + isolate_home(Some("/iso".to_string()), &home.join(".claude")), PathBuf::from("/iso") ); - assert_eq!(config_path(home), PathBuf::from("/home/u/.claude.json")); - assert_eq!(claude_dir(home), PathBuf::from("/home/u/.claude")); + // Both defaults hang off Claude Code's config directory, so they + // follow $CLAUDE_CONFIG_DIR with it. + let moved = Path::new("/opt/claude-work"); + assert_eq!( + ccswitch_home(None, moved), + PathBuf::from("/opt/claude-work/accounts") + ); + assert_eq!( + isolate_home(None, moved), + PathBuf::from("/opt/claude-work/profiles") + ); } #[test] diff --git a/src/cli_shim.rs b/src/cli_shim.rs index 03ab95f..4d20233 100644 --- a/src/cli_shim.rs +++ b/src/cli_shim.rs @@ -8,7 +8,9 @@ //! logic — every branch of behavior lives in [`crate::cli`] — and is excluded //! from coverage. +use crate::claude_env::ClaudeEnv; use crate::cli::{self, App, Io, Paths, System}; +use crate::creds::sanitize_account; use crate::creds_shim::platform_store; use crate::error::{Error, Result}; use crate::store::{Store, TokenScope}; @@ -159,15 +161,26 @@ pub fn run() -> anyhow::Result<()> { }; let home = home_dir(); - let claude = cli::claude_dir(&home); + // Claude Code's state follows $CLAUDE_CONFIG_DIR — including the name of + // its Keychain item — so every path and the service name come from here. + let env = ClaudeEnv::new( + std::env::var("CLAUDE_CONFIG_DIR").ok(), + std::env::var("CLAUDE_SECURESTORAGE_CONFIG_DIR").ok(), + std::env::var("CLAUDE_CODE_CUSTOM_OAUTH_URL").ok(), + ); + let claude = env.config_dir(&home); let store = Store::new(cli::ccswitch_home( std::env::var("CCSWITCH_HOME").ok(), - &home, + &claude, )); - let creds = platform_store(claude.clone()); + let creds = platform_store( + env.credentials_dir(&home), + env.keychain_service(), + sanitize_account(&std::env::var("USER").unwrap_or_default()), + ); let paths = Paths { - config: cli::config_path(&home), - isolate_base: cli::isolate_home(std::env::var("CCSWITCH_ISOLATE_HOME").ok(), &home), + config: env.config_path(&home), + isolate_base: cli::isolate_home(std::env::var("CCSWITCH_ISOLATE_HOME").ok(), &claude), seed_default: claude, }; let system = RealSystem; diff --git a/src/creds.rs b/src/creds.rs index f701918..aca6200 100644 --- a/src/creds.rs +++ b/src/creds.rs @@ -1,11 +1,30 @@ //! Credential port: reading and writing the Claude Code OAuth credential //! blob from the platform store. //! -//! The [`CredentialStore`] trait and all decision logic (path selection, -//! empty handling) live here, together with the file-based implementation -//! used on Linux and Windows. The real macOS Keychain adapter, which shells -//! out to the `security` binary, lives in [`crate::creds_shim`] and is -//! excluded from coverage. +//! The [`CredentialStore`] trait and all decision logic (backend selection, +//! Keychain-vs-file arbitration, `security` exit-code classification) live +//! here, together with the file-based [`FileStore`]. The real macOS adapter +//! is a thin [`Keychain`] port over the `security` binary in +//! [`crate::creds_shim`], which is excluded from coverage. +//! +//! ## Why the Keychain alone is not enough +//! +//! Claude Code does not store its credential in the macOS Keychain +//! unconditionally: its store is a *composite*. It reads the Keychain first +//! and falls back to plaintext `~/.claude/.credentials.json`, and when a +//! Keychain write fails it migrates the credential to that file instead. In a +//! pure-SSH or otherwise headless session the login Keychain cannot be +//! unlocked without a GUI prompt, `security` exits 36 +//! (`errSecInteractionNotAllowed`), and Claude Code is therefore living +//! entirely in the plaintext file. +//! +//! A Keychain-only `ccswitch` is invisible to that: `read` sees nothing (so +//! `save` claims you are not signed in and `sync_current` silently drops a +//! rotated token), and `write` cannot land the incoming credential — so +//! `~/.claude.json` names the account you switched to while the live token +//! still belongs to the old one, and Claude Code reports you as signed out. +//! [`KeychainStore`] mirrors Claude Code's own arbitration so the two agree +//! in every environment. use crate::error::Result; use std::fs; @@ -40,6 +59,19 @@ pub trait CredentialStore { /// /// Returns an error if the store cannot be queried. fn account_attr(&self) -> Result>; + + /// Explain why [`read`](CredentialStore::read) found nothing, when the + /// store knows more than "it was absent" — e.g. an unreachable Keychain. + /// + /// Returns `None` when the store has nothing to add, in which case the + /// caller uses its own generic wording. + /// + /// # Errors + /// + /// Returns an error if the store cannot be queried. + fn unavailable_hint(&self) -> Result> { + Ok(None) + } } /// File-based credential store: keeps the blob in @@ -66,6 +98,19 @@ impl FileStore { pub fn path(&self) -> PathBuf { self.dir.join(".credentials.json") } + + /// Delete the credential file, treating an already-absent file as success. + /// + /// # Errors + /// + /// Returns an error if the file exists but cannot be removed. + pub fn remove(&self) -> Result<()> { + match fs::remove_file(self.path()) { + Ok(()) => Ok(()), + Err(err) if err.kind() == ErrorKind::NotFound => Ok(()), + Err(err) => Err(err.into()), + } + } } impl CredentialStore for FileStore { @@ -91,6 +136,312 @@ impl CredentialStore for FileStore { } } +// --------------------------------------------------------------------------- +// macOS Keychain, with the plaintext fallback Claude Code itself uses +// --------------------------------------------------------------------------- + +/// `security` exit status when the requested item is simply not in the +/// keychain (`errSecItemNotFound`). A genuine "signed out", not a failure. +const SEC_ITEM_NOT_FOUND: i32 = 44; + +/// Raw result of one `security` invocation. The [`Keychain`] port hands this +/// back unclassified so that every decision about it stays testable here. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct KeychainOutput { + /// Process exit status, or `None` when the process was killed by a signal. + pub code: Option, + /// Captured standard output (the blob, for `find-generic-password -w`). + pub stdout: String, + /// Captured standard error (the attribute dump, for `-g`). + pub stderr: String, +} + +impl KeychainOutput { + /// Whether `security` exited cleanly. + #[must_use] + pub fn succeeded(&self) -> bool { + self.code == Some(0) + } +} + +/// Port over the macOS `security` binary: one raw invocation, no decisions. +/// +/// Keeping this down to a single method puts *every* choice — which +/// subcommand, which service name, whether the secret travels on argv or +/// stdin — in [`KeychainStore`], where it is unit-testable against a fake that +/// records exactly what would have been run. +/// +/// The real adapter lives in [`crate::creds_shim`]. +pub trait Keychain { + /// Run `security` with `args`, optionally feeding `stdin` to it. + /// + /// # Errors + /// + /// Returns an error if `security` cannot be spawned. + fn run(&self, args: &[String], stdin: Option<&str>) -> Result; +} + +/// What the keychain had to say when asked for the credential. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeychainState { + /// The credential is present. + Found(String), + /// The keychain is readable and holds no credential. + Empty, + /// The keychain could not be consulted at all — locked, absent, or + /// requiring a GUI prompt that a headless/SSH session cannot show. + Unavailable, +} + +impl KeychainState { + /// Classify a `find-generic-password -w` result. + /// + /// Exit 0 with output means the blob; exit 0 with nothing and + /// [`SEC_ITEM_NOT_FOUND`] both mean "no credential stored"; anything else + /// (notably 36, `errSecInteractionNotAllowed`) means the keychain itself + /// is out of reach, which is a different situation entirely — the + /// credential may well exist, we just cannot see it. + #[must_use] + pub fn classify(output: &KeychainOutput) -> Self { + match output.code { + Some(0) => { + let blob = output.stdout.trim_end_matches('\n'); + if blob.is_empty() { + Self::Empty + } else { + Self::Found(blob.to_string()) + } + } + Some(SEC_ITEM_NOT_FOUND) => Self::Empty, + _ => Self::Unavailable, + } + } +} + +/// Pull the `acct` attribute out of a `find-generic-password -g` dump, which +/// `security` prints on **stdout** as `"acct"="somebody"`. Only the +/// password itself goes to stderr, so parsing that stream (as this tool used +/// to) never matched and left every profile with an empty attribute. +#[must_use] +pub fn parse_account_attr(stderr: &str) -> Option { + stderr.lines().find_map(|line| { + line.trim() + .strip_prefix("\"acct\"=\"") + .and_then(|rest| rest.strip_suffix('"')) + .map(str::to_string) + }) +} + +/// Longest `security -i` stdin command line Claude Code will use before +/// falling back to argv; mirrored so the two agree on the boundary. +const STDIN_COMMAND_LIMIT: usize = 4032; + +/// Characters Claude Code accepts in a Keychain account attribute. Anything +/// else and it substitutes [`FALLBACK_ACCOUNT`], so we must too — otherwise +/// the two store the credential under different accounts. +const FALLBACK_ACCOUNT: &str = "claude-code-user"; + +/// Normalize an account attribute the way Claude Code does. +#[must_use] +pub fn sanitize_account(name: &str) -> String { + let ok = !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); + if ok { + name.to_string() + } else { + FALLBACK_ACCOUNT.to_string() + } +} + +/// Lowercase hex encoding, for `security -X`. +fn hex_encode(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The macOS credential store: the login Keychain in front of the plaintext +/// `/.credentials.json` that Claude Code falls back to. +/// +/// Read and write mirror Claude Code's own composite store so the two never +/// disagree about which copy is authoritative: +/// +/// * **read** — the Keychain wins; anything else (empty *or* unreachable) +/// falls through to the file. +/// * **write** — try the Keychain and, on success, delete the file, because a +/// leftover plaintext copy is a stale credential waiting to be picked up the +/// next time the Keychain is unreachable. If the Keychain write fails, write +/// the file and drop the Keychain item so its stale copy cannot shadow us +/// from a GUI session. +/// +/// The credential never appears in `security`'s argv: it is hex-encoded and +/// the whole command is piped to `security -i`, so it is not visible in `ps` +/// to other users on the machine. Only a blob too large for the stdin limit +/// falls back to argv, which is what Claude Code does as well. +pub struct KeychainStore { + keychain: Box, + fallback: FileStore, + service: String, + default_account: String, +} + +impl KeychainStore { + /// Build a store over a [`Keychain`] adapter, the plaintext fallback, the + /// Keychain service name (see [`crate::claude_env::ClaudeEnv`], which + /// derives it from `$CLAUDE_CONFIG_DIR`), and the account attribute to use + /// when a profile carries none — the OS username, which is what Claude + /// Code looks items up by. + #[must_use] + pub fn new( + keychain: Box, + fallback: FileStore, + service: String, + default_account: String, + ) -> Self { + Self { + keychain, + fallback, + service, + default_account, + } + } + + /// Run one `security` subcommand against this store's service. + fn security(&self, verb: &str, extra: &[&str]) -> Result { + let mut args = vec![verb.to_string(), "-s".to_string(), self.service.clone()]; + args.extend(extra.iter().map(|a| (*a).to_string())); + self.keychain.run(&args, None) + } + + /// The current keychain state. + fn state(&self) -> Result { + Ok(KeychainState::classify( + &self.security("find-generic-password", &["-w"])?, + )) + } + + /// Store `blob` under `acct`, keeping it off argv when it fits. + fn store_password(&self, blob: &str, acct: &str) -> Result { + let hex = hex_encode(blob.as_bytes()); + let script = format!( + "add-generic-password -U -a \"{acct}\" -s \"{}\" -X \"{hex}\"\n", + self.service + ); + if script.len() <= STDIN_COMMAND_LIMIT { + return self.keychain.run(&["-i".to_string()], Some(&script)); + } + // Too long for one stdin command line; Claude Code drops to argv here + // too. The secret is momentarily visible in `ps` on this path. + let args = [ + "add-generic-password", + "-U", + "-a", + acct, + "-s", + &self.service, + "-X", + &hex, + ] + .map(str::to_string); + self.keychain.run(&args, None) + } +} + +impl CredentialStore for KeychainStore { + fn read(&self) -> Result> { + match self.state()? { + KeychainState::Found(blob) => Ok(Some(blob)), + // Empty *and* Unavailable fall through: Claude Code reads the + // plaintext file in both cases, so an SSH session sees the + // credential it is actually using. + KeychainState::Empty | KeychainState::Unavailable => self.fallback.read(), + } + } + + fn write(&self, blob: &str, acct: &str) -> Result<()> { + let acct = sanitize_account(if acct.is_empty() { + &self.default_account + } else { + acct + }); + // `security` keys an item by (service, account), so adding under a + // different account attribute would leave a second item behind and + // reads would pick an arbitrary one. Clear first. + let _ = self.security("delete-generic-password", &[]); + if self.store_password(blob, &acct)?.succeeded() { + return self.fallback.remove(); + } + self.fallback.write(blob, &acct)?; + let _ = self.security("delete-generic-password", &[]); + Ok(()) + } + + fn account_attr(&self) -> Result> { + Ok(parse_account_attr( + &self.security("find-generic-password", &["-g"])?.stdout, + )) + } + + fn unavailable_hint(&self) -> Result> { + if self.state()? != KeychainState::Unavailable { + return Ok(None); + } + Ok(Some(format!( + "no active credential found — the macOS Keychain is locked or unreachable \\ + (the usual case over SSH with no GUI login) and there is no fallback at {}; \\ + unlock it with 'security unlock-keychain', or sign in with 'claude' in this \\ + session to write the fallback", + self.fallback.path().display() + ))) + } +} + +/// Which credential backend to use, selected by `$CCSWITCH_CREDENTIALS`. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Backend { + /// Platform default: Keychain-with-file-fallback on macOS, file elsewhere. + #[default] + Auto, + /// Force the plaintext file, skipping the Keychain entirely. Useful on a + /// headless Mac where every `security` call is a dead end anyway. + File, +} + +impl Backend { + /// Parse the `$CCSWITCH_CREDENTIALS` value; anything unrecognized (or + /// unset) is [`Backend::Auto`]. + #[must_use] + pub fn from_env(var: Option<&str>) -> Self { + match var.map(|v| v.trim().to_ascii_lowercase()).as_deref() { + Some("file" | "plaintext") => Self::File, + _ => Self::Auto, + } + } +} + +/// Assemble the credential store for a platform and backend choice. +/// +/// `keychain` is `Some` only on macOS; passing `None`, or asking for +/// [`Backend::File`], yields the plaintext [`FileStore`]. +#[must_use] +pub fn select_store( + backend: Backend, + keychain: Option>, + credentials_dir: PathBuf, + service: String, + default_account: String, +) -> Box { + match (backend, keychain) { + (Backend::Auto, Some(keychain)) => Box::new(KeychainStore::new( + keychain, + FileStore::new(credentials_dir), + service, + default_account, + )), + _ => Box::new(FileStore::new(credentials_dir)), + } +} + /// Tighten a file's permissions to owner read/write only. #[cfg(unix)] pub(crate) fn set_permissions_600(path: &Path) -> Result<()> { @@ -122,6 +473,8 @@ pub(crate) fn set_permissions_700(_path: &Path) -> Result<()> { #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; + use std::rc::Rc; fn temp_dir() -> PathBuf { use std::sync::atomic::{AtomicU64, Ordering}; @@ -256,6 +609,466 @@ mod tests { fs::remove_dir_all(&dir).unwrap(); } + // ---- the Keychain composite ------------------------------------------- + + /// Scriptable [`Keychain`] fake. Records every invocation — argv *and* + /// stdin — so tests can assert on what would really have been run. + /// One recorded `security` invocation: its argv and its stdin. + type CallLog = Rc, Option)>>>; + + struct FakeKeychain { + find: KeychainOutput, + attrs: KeychainOutput, + store_ok: bool, + calls: CallLog, + fail_find: bool, + fail_store: bool, + fail_attrs: bool, + } + + impl FakeKeychain { + fn new(find: KeychainOutput) -> Self { + Self { + find, + attrs: KeychainOutput::default(), + store_ok: true, + calls: Rc::new(RefCell::new(Vec::new())), + fail_find: false, + fail_store: false, + fail_attrs: false, + } + } + + /// A handle on the call log that outlives boxing into the store. + fn log(&self) -> CallLog { + Rc::clone(&self.calls) + } + } + + fn exit(code: i32, stdout: &str) -> KeychainOutput { + KeychainOutput { + code: Some(code), + stdout: stdout.to_string(), + stderr: String::new(), + } + } + + impl Keychain for FakeKeychain { + fn run(&self, args: &[String], stdin: Option<&str>) -> Result { + self.calls + .borrow_mut() + .push((args.to_vec(), stdin.map(str::to_string))); + let verb = args.first().map_or("", String::as_str); + if verb == "-i" || verb == "add-generic-password" { + if self.fail_store { + return Err(crate::error::Error::Invalid("spawn failed".to_string())); + } + return Ok(exit(i32::from(!self.store_ok), "")); + } + if verb == "delete-generic-password" { + return Ok(exit(0, "")); + } + if args.iter().any(|a| a == "-g") { + if self.fail_attrs { + return Err(crate::error::Error::Invalid("spawn failed".to_string())); + } + return Ok(self.attrs.clone()); + } + if self.fail_find { + return Err(crate::error::Error::Invalid("spawn failed".to_string())); + } + Ok(self.find.clone()) + } + } + + const TEST_SERVICE: &str = "Claude Code-credentials"; + + /// A `KeychainStore` over the fake, with its fallback in `dir`. + fn composite(keychain: FakeKeychain, dir: &Path) -> KeychainStore { + KeychainStore::new( + Box::new(keychain), + FileStore::new(dir), + TEST_SERVICE.to_string(), + "default-user".to_string(), + ) + } + + /// Flatten a call log to `argv` strings for easy assertions. + fn argv(log: &CallLog) -> Vec { + log.borrow().iter().map(|(a, _)| a.join(" ")).collect() + } + + /// The stdin script of the most recent call. + fn last_script(log: &CallLog) -> String { + log.borrow().last().unwrap().1.clone().unwrap() + } + + #[test] + fn classify_maps_every_security_outcome() { + assert_eq!( + KeychainState::classify(&exit(0, "BLOB\n")), + KeychainState::Found("BLOB".to_string()) + ); + assert_eq!(KeychainState::classify(&exit(0, "")), KeychainState::Empty); + assert_eq!(KeychainState::classify(&exit(44, "")), KeychainState::Empty); + // 36 is errSecInteractionNotAllowed — the SSH / headless case. + assert_eq!( + KeychainState::classify(&exit(36, "")), + KeychainState::Unavailable + ); + assert_eq!( + KeychainState::classify(&exit(1, "")), + KeychainState::Unavailable + ); + // Killed by a signal: no exit code at all. + assert_eq!( + KeychainState::classify(&KeychainOutput::default()), + KeychainState::Unavailable + ); + assert!(exit(0, "").succeeded()); + assert!(!exit(44, "").succeeded()); + } + + #[test] + fn parse_account_attr_reads_the_acct_blob() { + let dump = "keychain: \"/Users/x/Library/Keychains/login.keychain-db\"\n \ + \"acct\"=\"somebody\"\n \"svce\"=\"Claude Code-credentials\"\n"; + assert_eq!(parse_account_attr(dump).as_deref(), Some("somebody")); + assert_eq!(parse_account_attr("nothing here"), None); + // A truncated line must not be mistaken for a value. + assert_eq!(parse_account_attr("\"acct\"=\"unterminated"), None); + } + + #[test] + fn keychain_read_wins_over_the_fallback_file() { + let dir = temp_dir(); + let store = composite(FakeKeychain::new(exit(0, "KEYCHAIN\n")), &dir); + FileStore::new(&dir).write("STALE", "").unwrap(); + assert_eq!(store.read().unwrap().as_deref(), Some("KEYCHAIN")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn unreachable_keychain_reads_the_fallback_file() { + let dir = temp_dir(); + // Exit 36: the SSH session cannot unlock the login keychain, which is + // exactly when Claude Code is living in the plaintext file. + let store = composite(FakeKeychain::new(exit(36, "")), &dir); + FileStore::new(&dir).write("FALLBACK", "").unwrap(); + assert_eq!(store.read().unwrap().as_deref(), Some("FALLBACK")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn empty_keychain_reads_the_fallback_file() { + let dir = temp_dir(); + let store = composite(FakeKeychain::new(exit(44, "")), &dir); + FileStore::new(&dir).write("FALLBACK", "").unwrap(); + assert_eq!(store.read().unwrap().as_deref(), Some("FALLBACK")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn read_is_none_when_neither_backend_has_anything() { + let dir = temp_dir(); + let store = composite(FakeKeychain::new(exit(44, "")), &dir); + assert_eq!(store.read().unwrap(), None); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn read_propagates_a_keychain_spawn_failure() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(0, "")); + fake.fail_find = true; + let store = composite(fake, &dir); + assert!(store.read().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn successful_keychain_write_clears_the_stale_fallback_file() { + let dir = temp_dir(); + let file = FileStore::new(&dir); + file.write("STALE", "").unwrap(); + let store = composite(FakeKeychain::new(exit(0, "")), &dir); + store.write("FRESH", "somebody").unwrap(); + // Left in place, this file would resurface as the wrong account the + // next time the keychain is unreachable. + assert!(!file.path().exists()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn failed_keychain_write_falls_back_to_the_file_and_clears_the_keychain() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(36, "")); + fake.store_ok = false; + let store = composite(fake, &dir); + store.write("FRESH", "somebody").unwrap(); + assert_eq!( + FileStore::new(&dir).read().unwrap().as_deref(), + Some("FRESH") + ); + assert_eq!(store.read().unwrap().as_deref(), Some("FRESH")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn empty_account_attribute_falls_back_to_the_os_username() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "")); + let log = fake.log(); + // A profile saved before the attribute was captured carries none. + // Claude Code looks the item up by `-a `, so that is the + // only attribute under which it would still find the credential. + composite(fake, &dir).write("FRESH", "").unwrap(); + assert!(last_script(&log).contains("-a \"default-user\"")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_deletes_before_adding_so_no_duplicate_item_is_left() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "")); + let log = fake.log(); + composite(fake, &dir).write("FRESH", "somebody").unwrap(); + // Adding under a new acct without deleting first would leave a second + // item behind, and `find-generic-password -s` would pick either one. + assert_eq!( + argv(&log), + [ + format!("delete-generic-password -s {TEST_SERVICE}"), + "-i".to_string(), + ] + ); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn the_credential_never_reaches_security_argv() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "")); + let log = fake.log(); + composite(fake, &dir) + .write("SUPER-SECRET", "somebody") + .unwrap(); + + // `ps` shows argv to every user on the machine, so the blob must not + // be there — it goes down stdin to `security -i`, hex-encoded. + assert_eq!(argv(&log).last().unwrap(), "-i"); + assert!(!argv(&log).join(" ").contains("SUPER-SECRET")); + let script = last_script(&log); + assert!(!script.contains("SUPER-SECRET")); + assert!(script.starts_with("add-generic-password -U -a \"somebody\"")); + assert!(script.contains(&format!("-X \"{}\"", hex_encode(b"SUPER-SECRET")))); + assert!(script.ends_with('\n')); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn an_oversized_blob_falls_back_to_argv_like_claude_code() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "")); + let log = fake.log(); + // Hex doubles the blob, so this comfortably exceeds the stdin limit. + let huge = "x".repeat(STDIN_COMMAND_LIMIT); + composite(fake, &dir).write(&huge, "somebody").unwrap(); + + let calls = log.borrow(); + let (args, stdin) = calls.last().unwrap(); + assert_eq!(args[0], "add-generic-password"); + assert!(stdin.is_none()); + assert_eq!(args[args.len() - 2], "-X"); + drop(calls); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn hex_encoding_uses_the_expected_alphabet() { + assert_eq!(hex_encode(b""), ""); + assert_eq!(hex_encode(b"\x00\x0f\xff"), "000fff"); + assert_eq!(hex_encode("{}".as_bytes()), "7b7d"); + } + + #[test] + fn the_service_name_is_threaded_through_every_subcommand() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "BLOB")); + let log = fake.log(); + let store = KeychainStore::new( + Box::new(fake), + FileStore::new(&dir), + "Claude Code-credentials-deadbeef".to_string(), + "u".to_string(), + ); + store.read().unwrap(); + store.account_attr().unwrap(); + store.write("BLOB", "u").unwrap(); + // A store scoped to $CLAUDE_CONFIG_DIR must never touch the default + // item, or a switch inside an isolate swaps the main account. + for (args, stdin) in log.borrow().iter() { + let text = format!("{} {}", args.join(" "), stdin.clone().unwrap_or_default()); + assert!(text.contains("Claude Code-credentials-deadbeef"), "{text}"); + } + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn account_attributes_are_sanitized_like_claude_code() { + assert_eq!(sanitize_account("mysqto"), "mysqto"); + assert_eq!(sanitize_account("a.b_c-1"), "a.b_c-1"); + // Anything outside Claude Code's allowed set and it substitutes a + // fixed name — so we must, or we address a different item. + assert_eq!(sanitize_account(""), FALLBACK_ACCOUNT); + assert_eq!(sanitize_account("has space"), FALLBACK_ACCOUNT); + assert_eq!(sanitize_account("quote\"inject"), FALLBACK_ACCOUNT); + assert_eq!(sanitize_account("ünïcode"), FALLBACK_ACCOUNT); + } + + #[test] + fn a_hostile_account_name_cannot_break_out_of_the_stdin_script() { + let dir = temp_dir(); + let fake = FakeKeychain::new(exit(0, "")); + let log = fake.log(); + composite(fake, &dir) + .write("BLOB", "evil\" -s \"Claude Code-credentials") + .unwrap(); + let script = last_script(&log); + assert!(script.contains(&format!("-a \"{FALLBACK_ACCOUNT}\""))); + assert_eq!(script.matches("-s").count(), 1); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn write_propagates_a_keychain_spawn_failure() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(0, "")); + fake.fail_store = true; + let store = composite(fake, &dir); + assert!(store.write("FRESH", "somebody").is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn account_attr_comes_from_the_attribute_dump() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(0, "")); + fake.attrs = KeychainOutput { + code: Some(0), + stdout: " \"acct\"=\"somebody\"\n".to_string(), + // `-g` puts the secret, not the attributes, on stderr. + stderr: "password: \"{\\\"token\\\":1}\"\n".to_string(), + }; + let store = composite(fake, &dir); + assert_eq!(store.account_attr().unwrap().as_deref(), Some("somebody")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn account_attr_propagates_a_spawn_failure() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(0, "")); + fake.fail_attrs = true; + let store = composite(fake, &dir); + assert!(store.account_attr().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn hint_explains_an_unreachable_keychain_only() { + let dir = temp_dir(); + let store = composite(FakeKeychain::new(exit(36, "")), &dir); + let hint = store.unavailable_hint().unwrap().unwrap(); + assert!(hint.contains("Keychain is locked or unreachable")); + assert!(hint.contains(".credentials.json")); + + // A readable-but-empty keychain is a plain "signed out"; no hint. + let store = composite(FakeKeychain::new(exit(44, "")), &dir); + assert_eq!(store.unavailable_hint().unwrap(), None); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn hint_propagates_a_spawn_failure() { + let dir = temp_dir(); + let mut fake = FakeKeychain::new(exit(0, "")); + fake.fail_find = true; + let store = composite(fake, &dir); + assert!(store.unavailable_hint().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn file_store_has_no_hint() { + assert_eq!(FileStore::new("/x").unavailable_hint().unwrap(), None); + } + + #[test] + fn remove_is_idempotent_and_reports_real_failures() { + let dir = temp_dir(); + let store = FileStore::new(&dir); + // Absent is success. + store.remove().unwrap(); + store.write("blob", "").unwrap(); + store.remove().unwrap(); + assert!(!store.path().exists()); + // A directory at the credential path cannot be unlinked. + fs::create_dir_all(store.path()).unwrap(); + assert!(store.remove().is_err()); + fs::remove_dir_all(&dir).unwrap(); + } + + // ---- backend selection ------------------------------------------------- + + #[test] + fn backend_parses_the_env_var() { + assert_eq!(Backend::from_env(None), Backend::Auto); + assert_eq!(Backend::from_env(Some("")), Backend::Auto); + assert_eq!(Backend::from_env(Some("nonsense")), Backend::Auto); + assert_eq!(Backend::from_env(Some(" File ")), Backend::File); + assert_eq!(Backend::from_env(Some("PLAINTEXT")), Backend::File); + assert_eq!(Backend::default(), Backend::Auto); + } + + #[test] + fn select_store_picks_the_composite_only_when_asked_and_able() { + let dir = temp_dir(); + let file = FileStore::new(&dir); + file.write("FROM-FILE", "").unwrap(); + + // macOS default: the keychain is consulted first. + let store = select_store( + Backend::Auto, + Some(Box::new(FakeKeychain::new(exit(0, "FROM-KEYCHAIN")))), + dir.clone(), + TEST_SERVICE.to_string(), + "u".to_string(), + ); + assert_eq!(store.read().unwrap().as_deref(), Some("FROM-KEYCHAIN")); + + // Forced to the file even on macOS. + let store = select_store( + Backend::File, + Some(Box::new(FakeKeychain::new(exit(0, "FROM-KEYCHAIN")))), + dir.clone(), + TEST_SERVICE.to_string(), + "u".to_string(), + ); + assert_eq!(store.read().unwrap().as_deref(), Some("FROM-FILE")); + + // Off macOS there is no keychain to offer. + let store = select_store( + Backend::Auto, + None, + dir.clone(), + TEST_SERVICE.to_string(), + "u".to_string(), + ); + assert_eq!(store.read().unwrap().as_deref(), Some("FROM-FILE")); + fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn store_is_debuggable_and_cloneable() { let store = FileStore::new("/x"); diff --git a/src/creds_shim.rs b/src/creds_shim.rs index f499e22..d8db5ef 100644 --- a/src/creds_shim.rs +++ b/src/creds_shim.rs @@ -1,104 +1,73 @@ //! Real credential-store adapter (macOS `security` binary). //! -//! Side-effecting implementation of the [`crate::creds`] port. This is the -//! only place in the crate that runs the `security` binary, and it is -//! excluded from coverage. It contains no decision logic: platform selection -//! is a single `cfg` switch and each method is a thin wrapper over one -//! `security` invocation. +//! Side-effecting implementation of the [`crate::creds::Keychain`] port. This +//! is the only place in the crate that runs the `security` binary, and it is +//! excluded from coverage. It contains no decision logic: the single method +//! spawns `security` with the arguments it is handed, optionally feeding it +//! stdin, and returns the raw exit status and streams for +//! [`crate::creds`] to classify. Which subcommand runs, under which service +//! name, and whether the secret travels on stdin or argv are all decided +//! there; the store itself is assembled by [`crate::creds::select_store`]. -use crate::creds::CredentialStore; -#[cfg(not(target_os = "macos"))] -use crate::creds::FileStore; +use crate::creds::{select_store, Backend, CredentialStore}; +#[cfg(target_os = "macos")] +use crate::creds::{Keychain, KeychainOutput}; #[cfg(target_os = "macos")] -use crate::error::Error; use crate::error::Result; use std::path::PathBuf; -/// Service name under which Claude Code stores its OAuth credential. -#[cfg(target_os = "macos")] -const SERVICE: &str = "Claude Code-credentials"; - -/// Select the credential store for the current platform: the macOS Keychain -/// when available, otherwise the file-based fallback rooted at `config_dir`. +/// Select the credential store for the current platform and environment: the +/// macOS Keychain (backed by the plaintext fallback) when available, otherwise +/// the file-based store rooted at `credentials_dir`. +/// +/// `service` is the Keychain service name, which +/// [`crate::claude_env::ClaudeEnv::keychain_service`] derives from +/// `$CLAUDE_CONFIG_DIR`. #[must_use] -pub fn platform_store(config_dir: PathBuf) -> Box { +pub fn platform_store( + credentials_dir: PathBuf, + service: String, + default_account: String, +) -> Box { + let backend = Backend::from_env(std::env::var("CCSWITCH_CREDENTIALS").ok().as_deref()); #[cfg(target_os = "macos")] - { - let _ = config_dir; - Box::new(KeychainStore) - } + let keychain: Option> = Some(Box::new(SecurityBinary)); #[cfg(not(target_os = "macos"))] - { - Box::new(FileStore::new(config_dir)) - } + let keychain = None; + select_store(backend, keychain, credentials_dir, service, default_account) } -/// macOS Keychain credential store backed by the `security` binary. +/// macOS Keychain adapter backed by the `security` binary. #[cfg(target_os = "macos")] -pub struct KeychainStore; +pub struct SecurityBinary; #[cfg(target_os = "macos")] -impl CredentialStore for KeychainStore { - fn read(&self) -> Result> { - use std::process::Command; - let output = Command::new("security") - .args(["find-generic-password", "-s", SERVICE, "-w"]) - .output()?; - if !output.status.success() { - return Ok(None); - } - let blob = String::from_utf8_lossy(&output.stdout) - .trim_end_matches('\n') - .to_string(); - if blob.is_empty() { - Ok(None) - } else { - Ok(Some(blob)) - } - } +impl Keychain for SecurityBinary { + fn run(&self, args: &[String], stdin: Option<&str>) -> Result { + use std::io::Write; + use std::process::{Command, Stdio}; - fn write(&self, blob: &str, acct: &str) -> Result<()> { - use std::process::Command; - let acct = if acct.is_empty() { - std::env::var("USER").unwrap_or_default() - } else { - acct.to_string() - }; - let _ = Command::new("security") - .args(["delete-generic-password", "-s", SERVICE]) - .output(); - let status = Command::new("security") - .args([ - "add-generic-password", - "-U", - "-a", - &acct, - "-s", - SERVICE, - "-w", - blob, - ]) - .status()?; - if status.success() { - Ok(()) - } else { - Err(Error::Invalid("failed to write credential".to_string())) - } - } - - fn account_attr(&self) -> Result> { - use std::process::Command; - let output = Command::new("security") - .args(["find-generic-password", "-s", SERVICE, "-g"]) - .output()?; - let text = String::from_utf8_lossy(&output.stderr); - for line in text.lines() { - if let Some(rest) = line.trim().strip_prefix("\"acct\"=\"") { - if let Some(acct) = rest.strip_suffix('"') { - return Ok(Some(acct.to_string())); - } + let mut command = Command::new("security"); + command + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }); + let mut child = command.spawn()?; + if let Some(input) = stdin { + if let Some(mut pipe) = child.stdin.take() { + pipe.write_all(input.as_bytes())?; } } - Ok(None) + let output = child.wait_with_output()?; + Ok(KeychainOutput { + code: output.status.code(), + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }) } } diff --git a/src/lib.rs b/src/lib.rs index c7fb783..9a4606f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ //! while all decision logic lives in the plain modules and is unit-tested //! with fakes. +pub mod claude_env; pub mod cli; pub mod cli_shim; pub mod config; @@ -13,8 +14,10 @@ pub mod creds; pub mod creds_shim; pub mod error; pub mod model; +pub mod sha256; pub mod store; pub mod switch; +pub use claude_env::ClaudeEnv; pub use error::{Error, Result}; pub use model::{Account, Profile}; diff --git a/src/sha256.rs b/src/sha256.rs new file mode 100644 index 0000000..224461d --- /dev/null +++ b/src/sha256.rs @@ -0,0 +1,208 @@ +//! A small, dependency-free SHA-256. +//! +//! Claude Code namespaces its Keychain item by appending the first eight hex +//! characters of `sha256($CLAUDE_CONFIG_DIR)` to the service name, so +//! `ccswitch` has to compute the same digest to address the same item. That is +//! the only reason this exists — it is a naming hash, not a security +//! primitive, and the repo's dependency budget (see `AGENTS.md`) does not +//! stretch to the `sha2` crate and its six transitive dependencies for one +//! eight-character string. +//! +//! Implemented straight from FIPS 180-4 and checked against the standard test +//! vectors plus the multi-block and length-edge cases. + +/// The 64 round constants: the first 32 bits of the fractional parts of the +/// cube roots of the first 64 primes. +const K: [u32; 64] = [ + 0x428a_2f98, + 0x7137_4491, + 0xb5c0_fbcf, + 0xe9b5_dba5, + 0x3956_c25b, + 0x59f1_11f1, + 0x923f_82a4, + 0xab1c_5ed5, + 0xd807_aa98, + 0x1283_5b01, + 0x2431_85be, + 0x550c_7dc3, + 0x72be_5d74, + 0x80de_b1fe, + 0x9bdc_06a7, + 0xc19b_f174, + 0xe49b_69c1, + 0xefbe_4786, + 0x0fc1_9dc6, + 0x240c_a1cc, + 0x2de9_2c6f, + 0x4a74_84aa, + 0x5cb0_a9dc, + 0x76f9_88da, + 0x983e_5152, + 0xa831_c66d, + 0xb003_27c8, + 0xbf59_7fc7, + 0xc6e0_0bf3, + 0xd5a7_9147, + 0x06ca_6351, + 0x1429_2967, + 0x27b7_0a85, + 0x2e1b_2138, + 0x4d2c_6dfc, + 0x5338_0d13, + 0x650a_7354, + 0x766a_0abb, + 0x81c2_c92e, + 0x9272_2c85, + 0xa2bf_e8a1, + 0xa81a_664b, + 0xc24b_8b70, + 0xc76c_51a3, + 0xd192_e819, + 0xd699_0624, + 0xf40e_3585, + 0x106a_a070, + 0x19a4_c116, + 0x1e37_6c08, + 0x2748_774c, + 0x34b0_bcb5, + 0x391c_0cb3, + 0x4ed8_aa4a, + 0x5b9c_ca4f, + 0x682e_6ff3, + 0x748f_82ee, + 0x78a5_636f, + 0x84c8_7814, + 0x8cc7_0208, + 0x90be_fffa, + 0xa450_6ceb, + 0xbef9_a3f7, + 0xc671_78f2, +]; + +/// The lowercase hex SHA-256 digest of `data`. +#[must_use] +pub fn hex_digest(data: &[u8]) -> String { + let mut h: [u32; 8] = [ + 0x6a09_e667, + 0xbb67_ae85, + 0x3c6e_f372, + 0xa54f_f53a, + 0x510e_527f, + 0x9b05_688c, + 0x1f83_d9ab, + 0x5be0_cd19, + ]; + + // Pad to a multiple of 64 bytes: a 0x80 byte, zeroes, then the message + // length in bits as a big-endian u64. + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut msg = Vec::with_capacity(data.len() + 72); + msg.extend_from_slice(data); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_be_bytes()); + + for block in msg.as_chunks::<64>().0 { + let mut w = [0u32; 64]; + for (word, bytes) in w.iter_mut().zip(block.as_chunks::<4>().0) { + *word = u32::from_be_bytes(*bytes); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; + for (k, w) in K.iter().zip(w.iter()) { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ (!e & g); + let t1 = hh + .wrapping_add(s1) + .wrapping_add(ch) + .wrapping_add(*k) + .wrapping_add(*w); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + + for (slot, value) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *slot = slot.wrapping_add(value); + } + } + + h.iter().map(|word| format!("{word:08x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_fips_test_vectors() { + assert_eq!( + hex_digest(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + hex_digest(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + hex_digest(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + } + + #[test] + fn handles_multi_block_and_padding_edges() { + // 55 bytes: the last message that still fits its padding in one block. + assert_eq!( + hex_digest(&[b'a'; 55]), + "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318" + ); + // 56 bytes: forces a second block for the length field. + assert_eq!( + hex_digest(&[b'a'; 56]), + "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" + ); + // 64 bytes: exactly one block of message. + assert_eq!( + hex_digest(&[b'a'; 64]), + "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" + ); + // Well past one block. + assert_eq!( + hex_digest(&[b'a'; 1000]), + "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3" + ); + } + + #[test] + fn digests_a_realistic_config_dir_path() { + // The shape ccswitch actually hashes. + assert_eq!( + &hex_digest(b"/Users/someone/.claude-work")[..8], + &hex_digest(b"/Users/someone/.claude-work")[..8] + ); + assert_ne!( + hex_digest(b"/Users/someone/.claude-work"), + hex_digest(b"/Users/someone/.claude-home") + ); + } +} diff --git a/src/switch.rs b/src/switch.rs index e3b86c9..afd01ed 100644 --- a/src/switch.rs +++ b/src/switch.rs @@ -82,9 +82,15 @@ impl<'a> Switcher<'a> { "profile '{name}' already exists (pass --force to overwrite)" ))); } - let blob = self.creds.read()?.ok_or_else(|| { - Error::Invalid("no active credential found — sign in with 'claude' first".to_string()) - })?; + let Some(blob) = self.creds.read()? else { + // The store may know *why* it came up empty (an unreachable + // Keychain reads the same as a signed-out one, but is not). + return Err(Error::Invalid( + self.creds.unavailable_hint()?.unwrap_or_else(|| { + "no active credential found — sign in with 'claude' first".to_string() + }), + )); + }; let config = config::load(&self.config_path)?; let snapshot = self.identity_snapshot(&config)?; self.store.save_profile(name, &blob, &snapshot)?; @@ -187,6 +193,7 @@ mod tests { fail_read: bool, fail_write: bool, fail_acct: bool, + hint: Option, } impl FakeCredentialStore { @@ -197,6 +204,7 @@ mod tests { fail_read: false, fail_write: false, fail_acct: false, + hint: None, } } } @@ -223,6 +231,10 @@ mod tests { } Ok(self.acct.clone()) } + + fn unavailable_hint(&self) -> Result> { + Ok(self.hint.clone()) + } } fn temp_dir() -> PathBuf { @@ -328,6 +340,19 @@ mod tests { fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn save_without_credential_prefers_the_store_hint() { + let dir = temp_dir(); + let config = write_config(&dir, &config_json("A", "O1", "a@x", "uid-a")); + let store = Store::new(dir.join("accounts")); + let mut creds = FakeCredentialStore::with(None, None); + creds.hint = Some("the Keychain is unreachable".to_string()); + let switcher = Switcher::new(&creds, &store, &config, TokenScope::PerAccount); + let err = switcher.save("orga", false).unwrap_err(); + assert!(matches!(err, Error::Invalid(msg) if msg == "the Keychain is unreachable")); + fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn save_propagates_credential_read_error() { let dir = temp_dir(); diff --git a/tests/smoke.rs b/tests/smoke.rs index 6852a01..cefc8ca 100644 --- a/tests/smoke.rs +++ b/tests/smoke.rs @@ -1,6 +1,7 @@ //! Smoke test: the crate's public pure helpers behave as documented. use ccswitch::cli; +use ccswitch::ClaudeEnv; use std::path::Path; #[test] @@ -13,9 +14,30 @@ fn help_text_and_reserved_words_are_public() { #[test] fn default_paths_resolve_under_home() { let home = Path::new("/home/example"); - assert_eq!( - cli::ccswitch_home(None, home), - home.join(".claude").join("accounts") + let env = ClaudeEnv::default(); + let claude = env.config_dir(home); + assert_eq!(claude, home.join(".claude")); + assert_eq!(cli::ccswitch_home(None, &claude), claude.join("accounts")); + assert_eq!(cli::isolate_home(None, &claude), claude.join("profiles")); + assert_eq!(env.config_path(home), home.join(".claude.json")); + assert_eq!(env.keychain_service(), "Claude Code-credentials"); +} + +#[test] +fn claude_config_dir_moves_the_whole_account_including_the_keychain_item() { + let home = Path::new("/home/example"); + let env = ClaudeEnv::new(Some("/opt/claude-work".to_string()), None, None); + let claude = env.config_dir(home); + assert_eq!(claude, Path::new("/opt/claude-work")); + assert_eq!(env.config_path(home), claude.join(".claude.json")); + assert_eq!(env.credentials_dir(home), claude); + assert_eq!(cli::ccswitch_home(None, &claude), claude.join("accounts")); + // Crucially a *different* Keychain item from the default account's. + assert_ne!( + env.keychain_service(), + ClaudeEnv::default().keychain_service() ); - assert_eq!(cli::config_path(home), home.join(".claude.json")); + assert!(env + .keychain_service() + .starts_with("Claude Code-credentials-")); }