Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/token-cache-bound-to-credential.md
Original file line number Diff line number Diff line change
@@ -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.
91 changes: 85 additions & 6 deletions crates/google-workspace-cli/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -245,6 +281,7 @@ async fn get_token_inner(
creds: Credential,
token_cache_path: &std::path::Path,
) -> anyhow::Result<String> {
let fingerprint = credential_fingerprint(&creds);
match creds {
Credential::AuthorizedUser(ref secret) => {
// If proxy env vars are set, use reqwest directly (it supports proxy)
Expand All @@ -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")?;
Expand All @@ -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()
Expand Down Expand Up @@ -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 {
Expand Down
57 changes: 56 additions & 1 deletion crates/google-workspace-cli/src/auth_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PathBuf> {
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).
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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<String> = vec![];
Expand Down
Loading