cli icon indicating copy to clipboard operation
cli copied to clipboard

Drive API returns 403 for non-project-member users due to unnecessary x-goog-user-project header

Open anthonygaZG opened this issue 7 months ago • 4 comments

When using the gws CLI with an OAuth desktop app flow, Drive API calls fail with a 403 Forbidden error for users who are not IAM members of the GCP project specified in client_secret.json. Gmail and Calendar API calls succeed for the same user with the same credentials.

Error:

Caller does not have required permission to use project [project-id].
Grant the caller the roles/serviceusage.serviceUsageConsumer role,
or a custom role with the serviceusage.services.use permission.

Root cause: The CLI reads project_id from client_secret.json and sends it as the x-goog-user-project header on API requests. This triggers a GCP IAM check requiring the caller to have serviceusage.services.use on the specified project. For users who are not project members (common when distributing an OAuth app org-wide), this check fails.

Why this is unexpected: Google Workspace APIs are designed to attribute quota to the project that owns the OAuth client ID automatically via the token. Explicitly sending x-goog-user-project is unnecessary for Workspace API calls and introduces an IAM requirement that doesn't need to exist. Gmail and Calendar appear to handle this more leniently, but Drive strictly enforces it, resulting in inconsistent behavior across Workspace APIs.

Expected behavior: All Workspace API calls should succeed for any authenticated user without requiring IAM roles on the GCP project, since quota attribution happens automatically through the OAuth client ID.

Steps to reproduce:

  1. Create an OAuth desktop app client in a GCP project
  2. Distribute client_secret.json (with project_id field) to a user who has no IAM roles on the project
  3. User authenticates: gws auth login -s drive,gmail,calendar
  4. User runs a Gmail command — succeeds
  5. User runs a Calendar command — succeeds
  6. User runs a Drive command — fails with 403

Workaround: Grant roles/serviceusage.serviceUsageConsumer to all users on the GCP project.

Suggested fix: Do not send the x-goog-user-project header when using OAuth desktop app credentials for Workspace API calls, or make it opt-in rather than automatic.

Environment:

  • gws CLI version: 0.22.5
  • OS: macOS (Apple Silicon)
  • Auth method: OAuth desktop app flow

anthonygaZG avatar Apr 16 '26 16:04 anthonygaZG

Alternative workaround: Set GOOGLE_WORKSPACE_PROJECT_ID to the numeric project number (not name) extracted from the OAuth client ID:

export GOOGLE_WORKSPACE_PROJECT_ID=$(echo "$CLIENT_ID" | cut -d'-' -f1)
# or from token file:
export GOOGLE_WORKSPACE_PROJECT_ID=$(jq -r '.client_id | split("-")[0]' ~/.config/gws/credentials.json)

This works because the numeric project ID correctly attributes quota without triggering the IAM check. The issue is that gws uses the project name from client_secret.json, but quota attribution needs the numeric ID from the client_id prefix (format: {project_number}-{hash}.apps.googleusercontent.com).

This avoids needing to grant roles/serviceusage.serviceUsageConsumer to users.

thadreber-web avatar Apr 26 '26 19:04 thadreber-web

I can reproduce the same behavior with admin-reports, not just Drive.

In my case, the failing command was:

gws admin-reports activities list   --params '{"userKey":"all","applicationName":"login","maxResults":1}'

Auth was successful and included the required Reports scopes:

https://www.googleapis.com/auth/admin.reports.audit.readonly
https://www.googleapis.com/auth/admin.reports.usage.readonly

The request still failed with:

{
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "reason": "insufficientPermissions"
  }
}

I tested this by patching cli/crates/google-workspace-cli/src/executor.rs to stop sending x-goog-user-project:

/*
if let Some(quota_project) = crate::auth::get_quota_project() {
    request = request.header("x-goog-user-project", quota_project);
}
*/

After rebuilding without that header, the same admin-reports command succeeded.

This also affects Admin SDK / Reports API calls. The error differs from Drive’s serviceusage.services.use failure, but the trigger is the same: gws adds x-goog-user-project from client_secret.json, and the API rejects the request unless the Workspace user is also an IAM member on that GCP project.

That breaks the normal shared OAuth desktop-app case. A Workspace admin using the app should not also need IAM access to the app’s backing GCP project.

The header should be opt-in, or skipped for Workspace APIs that reject it.

snacsnoc avatar Apr 27 '26 21:04 snacsnoc

Independent confirmation on gws 0.22.5 / macOS (Apple Silicon), OAuth desktop-app flow — plus two corrections to the diagnosis above, both of which make this worse than reported.

1. Gmail is not lenient — the split is helper vs raw Discovery, not API vs API

The report says Gmail and Calendar succeed while Drive strictly enforces, and infers per-API leniency. My data says otherwise: Gmail raw Discovery calls fail with exactly this 403, while Gmail helper commands succeed against the same message ID, same token, same session:

Command Result
gws gmail +triage 200 — unread summary
gws gmail +read --id <MSG_ID> 200 — full body + attachment filenames
gws gmail users messages get --params '{"userId":"me","id":"<MSG_ID>","format":"minimal"}' 403 serviceusage
gws gmail users messages attachments get … 403 serviceusage
gws gmail users messages modify … (archive/label) 403 serviceusage

Same API, same mailbox, same credentials — so the differentiator is request construction, not the API's strictness. GOOGLE_WORKSPACE_CLI_LOG=trace shows the raw path emitting api_method="gmail.users.messages.get" http_method=GET status=403 while the helper path reaches the endpoint and returns 200.

I suspect the original report tested Gmail via helpers and Drive via raw calls, which would produce the "Drive is stricter" appearance. If so, the blast radius is larger than reported: it is every raw Discovery call on every Workspace API, with the helpers masking it.

2. The suggested workaround is impossible for an entire class of users

Workaround: Grant roles/serviceusage.serviceUsageConsumer to all users on the GCP project.

This cannot be done when the OAuth client's project lives in a Cloud org that enforces Domain Restricted Sharing (constraints/iam.allowedPolicyMemberDomains) and the authenticating user is outside that org — e.g. a consumer @gmail.com account. The grant is not merely un-granted; it is refused by policy:

$ gcloud projects add-iam-policy-binding <org-project-id> \
    --member="user:<external-account>@gmail.com" \
    --role="roles/serviceusage.serviceUsageConsumer"

ERROR: (gcloud.projects.add-iam-policy-binding) FAILED_PRECONDITION:
One or more users named in the policy do not belong to a permitted customer.
  description: User <external-account>@gmail.com is not in permitted organization.
  type: constraints/iam.allowedPolicyMemberDomains

Ruled out as causes (all verified on the project): billing enabled; gmail.googleapis.com enabled; serviceusage.googleapis.com enabled. Re-running gws auth login does not help — the token was never the problem.

So for this configuration — an OAuth client distributed from an org project, used by an account outside the org — there is no workaround at all, and gws is unusable for anything beyond the helper surface. That seems worth factoring into the priority of the suggested fix (don't send x-goog-user-project, or make it opt-in).

3. No override exists in 0.22.5

For completeness, since #261/#273 might suggest otherwise: v0.22.5 has no way to override or suppress the quota project. The only env vars the binary references are GOOGLE_WORKSPACE_CLI_{CLIENT_ID,CLIENT_SECRET,CONFIG_DIR,CREDENTIALS_FILE,KEYRING_BACKEND,LOG,LOG_FILE,SANITIZE_MODE,SANITIZE_TEMPLATE,TOKEN} plus GOOGLE_APPLICATION_CREDENTIALS. There is no GOOGLE_CLOUD_QUOTA_PROJECT and no CLI flag.

Removing project_id from client_secret.json does not suppress the header either — it silently falls back to the ambient gcloud ADC quota_project_id, which is a separate problem I've filed separately.

Happy to test a patch against this configuration if that would help.

alexey-pelykh avatar Jul 17 '26 14:07 alexey-pelykh

Confirming this from another organization, with one difference worth noting.

Environment: gws 0.22.5, macOS 26.5.2 (Apple Silicon), OAuth desktop app flow, client_secret.json containing a project_id for a GCP project the authenticating user had no IAM roles on.

Difference from the original report: this issue states that Gmail and Calendar succeed while Drive fails. In our case every Workspace API failed, all with the identical error:

Caller does not have required permission to use project [PROJECT_ID].
Grant the caller the roles/serviceusage.serviceUsageConsumer role,
or a custom role with the serviceusage.services.use permission.

Confirmed failing: Drive, Gmail, Calendar, Sheets, Docs, and Slides. So the strict enforcement may not be Drive-specific — it may vary by project configuration or have broadened over time.

Two details that made this hard to diagnose:

  1. gws auth status reported token_valid: true with all scopes granted throughout. Every signal in the CLI said authentication was healthy while every request was being rejected, which sent us looking in the wrong place for some time.

  2. Setting GOOGLE_WORKSPACE_PROJECT_ID="" does not detach the project — it falls back to the project_id in client_secret.json. Setting it to a non-existent project changes the error to Project not found, which confirms the header is being sent, but there appears to be no supported way to omit it.

Resolution: granting roles/serviceusage.serviceUsageConsumer on the project fixed all six APIs immediately, no re-authentication needed.

This is a meaningful onboarding obstacle when an OAuth client is distributed org-wide, since each new user needs an IAM grant on a Cloud project they otherwise have no reason to touch. A troubleshooting entry mapping this error to the required role would help even if the header behavior stays as-is.

grahamtyler-gw avatar Jul 28 '26 22:07 grahamtyler-gw