diff --git a/.changeset/token-cache-bound-to-credential.md b/.changeset/token-cache-bound-to-credential.md new file mode 100644 index 0000000000..621bcf32e7 --- /dev/null +++ b/.changeset/token-cache-bound-to-credential.md @@ -0,0 +1,5 @@ +--- +"@googleworkspace/cli": patch +--- + +Stop serving a stale access token after the credentials change. `gws auth login` now clears the token caches, and cached tokens are bound to a fingerprint of the credential that minted them, so a re-login with new scopes, a login to another account, or switching `GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE` never reuses the previous credential's token. diff --git a/crates/google-workspace-cli/src/auth.rs b/crates/google-workspace-cli/src/auth.rs index 9d8847e4be..a05f07d538 100644 --- a/crates/google-workspace-cli/src/auth.rs +++ b/crates/google-workspace-cli/src/auth.rs @@ -133,6 +133,42 @@ enum Credential { ServiceAccount(yup_oauth2::ServiceAccountKey), } +/// Returns a stable, non-secret digest identifying a credential, used to bind +/// cached access tokens to the credential that minted them. +/// +/// For a user credential the refresh token identifies the grant, so a new +/// `gws auth login` (another account, or the same account with other scopes) +/// yields a new fingerprint. For a service account the key ID identifies the +/// key. The digest is a truncated SHA-256, so it reveals nothing about the +/// secrets it is derived from. +fn credential_fingerprint(creds: &Credential) -> String { + use sha2::{Digest, Sha256}; + + let mut hasher = Sha256::new(); + let mut field = |value: &str| { + // Length-prefix each field so different splits can never collide. + hasher.update((value.len() as u64).to_be_bytes()); + hasher.update(value.as_bytes()); + }; + match creds { + Credential::AuthorizedUser(secret) => { + field("authorized_user"); + field(&secret.client_id); + field(&secret.refresh_token); + } + Credential::ServiceAccount(key) => { + field("service_account"); + field(&key.client_email); + field(key.private_key_id.as_deref().unwrap_or("")); + field(&key.private_key); + } + } + hasher.finalize()[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + /// Fetches access tokens for a fixed set of scopes. /// /// Long-running helpers use this trait so they can request a fresh token before @@ -245,6 +281,7 @@ async fn get_token_inner( creds: Credential, token_cache_path: &std::path::Path, ) -> anyhow::Result { + let fingerprint = credential_fingerprint(&creds); match creds { Credential::AuthorizedUser(ref secret) => { // If proxy env vars are set, use reqwest directly (it supports proxy) @@ -260,9 +297,12 @@ async fn get_token_inner( // No proxy - use yup-oauth2 (faster, has token caching) let auth = yup_oauth2::AuthorizedUserAuthenticator::builder(secret.clone()) - .with_storage(Box::new(crate::token_storage::EncryptedTokenStorage::new( - token_cache_path.to_path_buf(), - ))) + .with_storage(Box::new( + crate::token_storage::EncryptedTokenStorage::new( + token_cache_path.to_path_buf(), + ) + .with_credential_fingerprint(fingerprint), + )) .build() .await .context("Failed to build authorized user authenticator")?; @@ -279,9 +319,11 @@ async fn get_token_inner( .map(|f| f.to_string_lossy().to_string()) .unwrap_or_else(|| "token_cache.json".to_string()); let sa_cache = token_cache_path.with_file_name(format!("sa_{tc_filename}")); - let builder = yup_oauth2::ServiceAccountAuthenticator::builder(key).with_storage( - Box::new(crate::token_storage::EncryptedTokenStorage::new(sa_cache)), - ); + let builder = + yup_oauth2::ServiceAccountAuthenticator::builder(key).with_storage(Box::new( + crate::token_storage::EncryptedTokenStorage::new(sa_cache) + .with_credential_fingerprint(fingerprint), + )); let auth = builder .build() @@ -439,6 +481,43 @@ mod tests { use std::io::Write; use tempfile::NamedTempFile; + fn user_credential(client_id: &str, refresh_token: &str) -> Credential { + Credential::AuthorizedUser(yup_oauth2::authorized_user::AuthorizedUserSecret { + client_id: client_id.to_string(), + client_secret: "secret".to_string(), + refresh_token: refresh_token.to_string(), + key_type: "authorized_user".to_string(), + }) + } + + #[test] + fn test_credential_fingerprint_tracks_the_grant() { + let a = credential_fingerprint(&user_credential("client", "refresh-a")); + // Stable for the same credential. + assert_eq!( + a, + credential_fingerprint(&user_credential("client", "refresh-a")) + ); + // A re-login (new refresh token) or another client changes it. + assert_ne!( + a, + credential_fingerprint(&user_credential("client", "refresh-b")) + ); + assert_ne!( + a, + credential_fingerprint(&user_credential("other", "refresh-a")) + ); + // Field boundaries are unambiguous. + assert_ne!( + credential_fingerprint(&user_credential("ab", "c")), + credential_fingerprint(&user_credential("a", "bc")) + ); + // Short hex digest that never embeds the secret. + assert_eq!(a.len(), 32); + assert!(a.chars().all(|c| c.is_ascii_hexdigit())); + assert!(!a.contains("refresh")); + } + /// RAII guard that saves the current value of an environment variable and /// restores it when dropped. This ensures cleanup even if a test panics. struct EnvVarGuard { diff --git a/crates/google-workspace-cli/src/auth_commands.rs b/crates/google-workspace-cli/src/auth_commands.rs index d7571e7478..ee043e8724 100644 --- a/crates/google-workspace-cli/src/auth_commands.rs +++ b/crates/google-workspace-cli/src/auth_commands.rs @@ -345,6 +345,29 @@ fn token_cache_path() -> PathBuf { config_dir().join("token_cache.json") } +fn sa_token_cache_path() -> PathBuf { + config_dir().join("sa_token_cache.json") +} + +/// Removes the given token cache files, ignoring ones that do not exist. +/// Returns the paths that were removed. A file that cannot be removed only +/// produces a warning: cached entries are also bound to the credential that +/// minted them, so a leftover cache is ignored rather than reused. +fn clear_token_caches(paths: &[PathBuf]) -> Vec { + let mut removed = Vec::new(); + for path in paths { + match std::fs::remove_file(path) { + Ok(()) => removed.push(path.clone()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => eprintln!( + "warning: failed to remove token cache {}: {e}", + path.display() + ), + } + } + removed +} + /// Which scope set to use for login. enum ScopeMode { /// Use the default scopes (MINIMAL_SCOPES). @@ -644,6 +667,13 @@ async fn handle_login_inner( let enc_path = credential_store::save_encrypted(&creds_str) .map_err(|e| GwsError::Auth(format!("Failed to encrypt credentials: {e}")))?; + // Cached access tokens (and the refresh tokens yup-oauth2 stores beside + // them) belong to the previous login: another account, or the same + // account under the old scopes. Drop them so the next call mints a token + // from the credentials just saved (#780, #572). + clear_token_caches(&[token_cache_path(), sa_token_cache_path()]); + crate::timezone::invalidate_cache(); + let output = json!({ "status": "success", "message": "Authentication successful. Encrypted credentials saved.", @@ -1457,7 +1487,7 @@ fn handle_logout() -> Result<(), GwsError> { let plain_path = plain_credentials_path(); let enc_path = credential_store::encrypted_credentials_path(); let token_cache = token_cache_path(); - let sa_token_cache = config_dir().join("sa_token_cache.json"); + let sa_token_cache = sa_token_cache_path(); let mut removed = Vec::new(); @@ -1900,6 +1930,31 @@ mod tests { assert!(path.starts_with(config_dir())); } + #[test] + fn clear_token_caches_removes_existing_and_skips_missing() { + let dir = tempfile::tempdir().unwrap(); + let cache = dir.path().join("token_cache.json"); + let sa_cache = dir.path().join("sa_token_cache.json"); + std::fs::write(&cache, b"stale").unwrap(); + + let removed = clear_token_caches(&[cache.clone(), sa_cache.clone()]); + + assert_eq!(removed, vec![cache.clone()]); + assert!(!cache.exists()); + assert!(!sa_cache.exists()); + // Idempotent. + assert!(clear_token_caches(&[cache, sa_cache]).is_empty()); + } + + #[test] + fn token_cache_paths_live_in_config_dir() { + assert_eq!(token_cache_path(), config_dir().join("token_cache.json")); + assert_eq!( + sa_token_cache_path(), + config_dir().join("sa_token_cache.json") + ); + } + #[tokio::test] async fn handle_auth_command_empty_args_prints_usage() { let args: Vec = vec![]; diff --git a/crates/google-workspace-cli/src/token_storage.rs b/crates/google-workspace-cli/src/token_storage.rs index 5fb17a0066..7d0df19bcc 100644 --- a/crates/google-workspace-cli/src/token_storage.rs +++ b/crates/google-workspace-cli/src/token_storage.rs @@ -22,20 +22,43 @@ use crate::output::sanitize_for_terminal; /// A custom token storage implementation for `yup-oauth2` that encrypts /// the cached tokens at rest using AES-256-GCM encryption. +/// +/// Cached tokens can be bound to the credential that minted them (see +/// [`EncryptedTokenStorage::with_credential_fingerprint`]). yup-oauth2 stores +/// the refresh token alongside each cached access token and refreshes expired +/// entries with that stored refresh token, so an unbound cache keeps serving +/// the previous account (or the previous scope grant) after the credentials +/// change. Binding the entries to a fingerprint of the credential makes a +/// cache written for one credential invisible to every other credential. pub struct EncryptedTokenStorage { file_path: PathBuf, + /// Fingerprint of the credential this storage serves; entries written for + /// any other credential are ignored on read and pruned on write. + credential_fingerprint: Option, // Add memory cache since TokenStorage getters can be called frequently cache: Arc>>>, } +/// Separates the credential fingerprint from the scope list in cache keys. +/// Scopes are URLs or short names and never contain this character. +const FINGERPRINT_SEPARATOR: char = '|'; + impl EncryptedTokenStorage { pub fn new(path: PathBuf) -> Self { Self { file_path: path, + credential_fingerprint: None, cache: Arc::new(Mutex::new(None)), } } + /// Binds cached tokens to the credential identified by `fingerprint` + /// (an opaque, non-secret digest; see `auth::credential_fingerprint`). + pub fn with_credential_fingerprint(mut self, fingerprint: impl Into) -> Self { + self.credential_fingerprint = Some(fingerprint.into()); + self + } + async fn load_from_disk(&self) -> HashMap { let data = match tokio::fs::read(&self.file_path).await { Ok(d) => d, @@ -111,12 +134,34 @@ impl EncryptedTokenStorage { } // Helper to join scopes consistently for cache keys - fn cache_key(scopes: &[&str]) -> String { + fn scope_key(scopes: &[&str]) -> String { let mut s: Vec<&str> = scopes.to_vec(); s.sort_unstable(); s.dedup(); s.join(" ") } + + /// Cache key for `scopes`, prefixed with the credential fingerprint when + /// the storage is bound to a credential. + fn cache_key(&self, scopes: &[&str]) -> String { + let scopes = Self::scope_key(scopes); + match &self.credential_fingerprint { + Some(fp) => format!("{fp}{FINGERPRINT_SEPARATOR}{scopes}"), + None => scopes, + } + } + + /// Whether a stored entry belongs to this storage's credential. Unbound + /// storage owns only unprefixed (legacy) keys; bound storage owns only keys + /// carrying its own fingerprint. + fn owns_key(&self, key: &str) -> bool { + match &self.credential_fingerprint { + Some(fp) => key + .strip_prefix(fp.as_str()) + .is_some_and(|rest| rest.starts_with(FINGERPRINT_SEPARATOR)), + None => !key.contains(FINGERPRINT_SEPARATOR), + } + } } #[async_trait::async_trait] @@ -130,7 +175,11 @@ impl TokenStorage for EncryptedTokenStorage { } if let Some(map) = map_lock.as_mut() { - map.insert(Self::cache_key(scopes), token); + // Drop entries minted for any other credential (a previous login, + // another account, or the legacy unbound format): they can never + // be served again and still hold that credential's refresh token. + map.retain(|key, _| self.owns_key(key)); + map.insert(self.cache_key(scopes), token); self.save_to_disk(map) .await .map_err(|e| TokenStorageError::Other(std::borrow::Cow::Owned(e.to_string())))?; @@ -147,7 +196,7 @@ impl TokenStorage for EncryptedTokenStorage { } if let Some(map) = map_lock.as_ref() { - let key = Self::cache_key(scopes); + let key = self.cache_key(scopes); if let Some(token) = map.get(&key) { return Some(token.clone()); } @@ -172,4 +221,114 @@ mod tests { let cache_lock = storage.cache.lock().await; assert!(cache_lock.is_none()); } + + fn token(access: &str) -> TokenInfo { + TokenInfo { + access_token: Some(access.to_string()), + refresh_token: Some(format!("refresh-for-{access}")), + expires_at: None, + id_token: None, + } + } + + #[test] + fn test_cache_key_is_scope_order_independent_and_prefixed() { + let unbound = EncryptedTokenStorage::new(PathBuf::from("/x")); + assert_eq!(unbound.cache_key(&["b", "a", "a"]), "a b"); + + let bound = + EncryptedTokenStorage::new(PathBuf::from("/x")).with_credential_fingerprint("fp1"); + assert_eq!(bound.cache_key(&["b", "a"]), "fp1|a b"); + } + + #[test] + fn test_owns_key() { + let unbound = EncryptedTokenStorage::new(PathBuf::from("/x")); + assert!(unbound.owns_key("a b")); + assert!(!unbound.owns_key("fp1|a b")); + + let bound = + EncryptedTokenStorage::new(PathBuf::from("/x")).with_credential_fingerprint("fp1"); + assert!(bound.owns_key("fp1|a b")); + assert!(!bound.owns_key("fp2|a b")); + assert!(!bound.owns_key("fp1x|a b")); + assert!(!bound.owns_key("a b")); + } + + /// Regression test for #780 / #572: a token cached for one credential must + /// never be served to another one sharing the same cache file. + #[tokio::test] + #[serial_test::serial] + async fn test_cache_is_not_shared_between_credentials() { + let dir = tempfile::tempdir().unwrap(); + let _config = ConfigDirGuard::set(dir.path()); + let path = dir.path().join("token_cache.json"); + let scopes = ["https://www.googleapis.com/auth/drive"]; + + let account_a = + EncryptedTokenStorage::new(path.clone()).with_credential_fingerprint("account-a"); + account_a.set(&scopes, token("token-a")).await.unwrap(); + assert_eq!( + account_a + .get(&scopes) + .await + .unwrap() + .access_token + .as_deref(), + Some("token-a") + ); + + // A fresh process for account B reads the same file from disk. + let account_b = + EncryptedTokenStorage::new(path.clone()).with_credential_fingerprint("account-b"); + assert!(account_b.get(&scopes).await.is_none()); + + // Writing B's token prunes A's entry (and its refresh token) from disk. + account_b.set(&scopes, token("token-b")).await.unwrap(); + let reread_a = + EncryptedTokenStorage::new(path.clone()).with_credential_fingerprint("account-a"); + assert!(reread_a.get(&scopes).await.is_none()); + let reread_b = EncryptedTokenStorage::new(path).with_credential_fingerprint("account-b"); + assert_eq!( + reread_b.get(&scopes).await.unwrap().access_token.as_deref(), + Some("token-b") + ); + } + + /// Caches written before entries were bound to a credential use bare + /// scope keys; bound storage must ignore them rather than trust them. + #[tokio::test] + #[serial_test::serial] + async fn test_bound_storage_ignores_legacy_unbound_entries() { + let dir = tempfile::tempdir().unwrap(); + let _config = ConfigDirGuard::set(dir.path()); + let path = dir.path().join("token_cache.json"); + let scopes = ["https://www.googleapis.com/auth/drive"]; + + let legacy = EncryptedTokenStorage::new(path.clone()); + legacy.set(&scopes, token("legacy")).await.unwrap(); + + let bound = EncryptedTokenStorage::new(path).with_credential_fingerprint("account-a"); + assert!(bound.get(&scopes).await.is_none()); + } + + /// Points the encryption key file at a temp dir for the test's duration. + struct ConfigDirGuard(Option); + + impl ConfigDirGuard { + fn set(dir: &std::path::Path) -> Self { + let original = std::env::var_os("GOOGLE_WORKSPACE_CLI_CONFIG_DIR"); + unsafe { std::env::set_var("GOOGLE_WORKSPACE_CLI_CONFIG_DIR", dir) }; + Self(original) + } + } + + impl Drop for ConfigDirGuard { + fn drop(&mut self) { + match &self.0 { + Some(v) => unsafe { std::env::set_var("GOOGLE_WORKSPACE_CLI_CONFIG_DIR", v) }, + None => unsafe { std::env::remove_var("GOOGLE_WORKSPACE_CLI_CONFIG_DIR") }, + } + } + } }