Skip to content
Open
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/restore-dwd-impersonation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@googleworkspace/cli": minor
---

Restore domain-wide delegation support for service accounts via `GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER` env var
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,22 @@ export GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE=/path/to/service-account.json
gws drive files list
```

#### Domain-Wide Delegation (DWD)

To access user data (Gmail, Calendar, etc.) via a service account with
[domain-wide delegation](https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority),
set the impersonated user:

```bash
export GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE=/path/to/service-account.json
export GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER=user@example.com
gws gmail users messages list --params '{"userId": "me"}'
```

> **Note:** Without `GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER`, service accounts
> can only access their own resources. User-scoped APIs like Gmail and Calendar
> require impersonation via DWD.

### Pre-obtained Access Token

Useful when another tool (e.g. `gcloud`) already mints tokens for your environment.
Expand Down Expand Up @@ -382,6 +398,7 @@ All variables are optional. See [`.env.example`](.env.example) for a copy-paste
|---|---|
| `GOOGLE_WORKSPACE_CLI_TOKEN` | Pre-obtained OAuth2 access token (highest priority) |
| `GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE` | Path to OAuth credentials JSON (user or service account) |
| `GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER` | Email to impersonate via domain-wide delegation (service accounts only) |
| `GOOGLE_WORKSPACE_CLI_CLIENT_ID` | OAuth client ID (alternative to `client_secret.json`) |
| `GOOGLE_WORKSPACE_CLI_CLIENT_SECRET` | OAuth client secret (paired with `CLIENT_ID`) |
| `GOOGLE_WORKSPACE_CLI_CONFIG_DIR` | Override config directory (default: `~/.config/gws`) |
Expand Down
20 changes: 18 additions & 2 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ use anyhow::Context;

use crate::credential_store;

const IMPERSONATED_USER_ENV: &str = "GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER";

/// Returns the impersonated user email for domain-wide delegation, if set.
pub fn get_impersonated_user() -> Option<String> {
std::env::var(IMPERSONATED_USER_ENV)
.ok()
.filter(|val| !val.trim().is_empty())
}

/// Returns the project ID to be used for quota and billing (sets the `x-goog-user-project` header).
///
/// Priority:
Expand Down Expand Up @@ -164,19 +173,21 @@ pub async fn get_token(scopes: &[&str]) -> anyhow::Result<String> {
}

let creds_file = std::env::var("GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE").ok();
let impersonated_user = get_impersonated_user();
let config_dir = crate::auth_commands::config_dir();
let enc_path = credential_store::encrypted_credentials_path();
let default_path = config_dir.join("credentials.json");
let token_cache = config_dir.join("token_cache.json");

let creds = load_credentials_inner(creds_file.as_deref(), &enc_path, &default_path).await?;
get_token_inner(scopes, creds, &token_cache).await
get_token_inner(scopes, creds, &token_cache, impersonated_user.as_deref()).await
}

async fn get_token_inner(
scopes: &[&str],
creds: Credential,
token_cache_path: &std::path::Path,
impersonated_user: Option<&str>,
) -> anyhow::Result<String> {
match creds {
Credential::AuthorizedUser(secret) => {
Expand All @@ -200,10 +211,15 @@ 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(
let mut builder = yup_oauth2::ServiceAccountAuthenticator::builder(key).with_storage(
Box::new(crate::token_storage::EncryptedTokenStorage::new(sa_cache)),
);

// Domain-wide delegation: set the impersonated user (sub claim) on the JWT
if let Some(user) = impersonated_user {
builder = builder.subject(user.to_string());
}

let auth = builder
.build()
.await
Expand Down
5 changes: 5 additions & 0 deletions src/auth_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -963,6 +963,11 @@ async fn handle_status() -> Result<(), GwsError> {
"token_cache_exists": has_token_cache,
});

// Show impersonated user if set (domain-wide delegation)
if let Some(user) = crate::auth::get_impersonated_user() {
output["impersonated_user"] = json!(user);
}

// Show client config (client_secret.json) status
let config_path = crate::oauth_config::client_config_path();
let has_config = config_path.exists();
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,7 @@ fn print_usage() {
println!(
" GOOGLE_WORKSPACE_CLI_KEYRING_BACKEND Keyring backend: keyring (default) or file"
);
println!(" GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER Email to impersonate via domain-wide delegation (SA only)");
println!(" GOOGLE_WORKSPACE_CLI_SANITIZE_TEMPLATE Default Model Armor template");
println!(
" GOOGLE_WORKSPACE_CLI_SANITIZE_MODE Sanitization mode: warn (default) or block"
Expand Down
Loading