cli icon indicating copy to clipboard operation
cli copied to clipboard

401: Failed to parse authorized user credentials on all API calls after successful gws auth login (v0.4.3, macOS)

Open raludi opened this issue 8 months ago • 5 comments

Description

After a successful gws auth login, all API calls fail with:

{
"error": {
"code": 401,
"message": "Gmail auth failed: Failed to parse authorized user credentials", "reason": "authError" } }

Environment

  • gws version: 0.4.3
  • OS: macOS (Darwin 25.3.0)
  • Encryption: AES-256-GCM with local .encryption_key

Steps to Reproduce

  1. gws auth setup → success
  2. gws auth login → completes OAuth flow, saves credentials.enc
  3. gws auth status → shows token_valid: true, correct scopes, encryption_valid: true
  4. gws gmail +triage → fails with 401
  5. gws gmail users messages list --params '{"userId": "me"}' → also fails with 401

Investigation

  • gws auth export works and shows (masked) credentials — confirming the encrypted file can be decrypted.
  • Manually decrypting credentials.enc using the .encryption_key with Node.js crypto.createDecipheriv('aes-256-gcm', ...) produces valid JSON with all fields (client_id, client_secret, refresh_token, type).
  • Exchanging the decrypted refresh_token for an access token via curl to https://oauth2.googleapis.com/token succeeds.
  • Using GOOGLE_WORKSPACE_CLI_TOKEN=<access_token> gws gmail +triage works correctly.

This confirms the credentials are valid but gws fails to parse them during API call authentication, despite successfully decrypting them during auth export and auth status.

Attempted Workarounds

  • Deleted .encryption_key + credentials.enc and re-ran gws auth login → same error
  • Exported credentials to a plain JSON file and set GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE → fails with Failed to get token
  • Setting GOOGLE_WORKSPACE_CLI_TOKEN with a manually obtained access token → works (but tokens expire after 1 hour)

raludi avatar Mar 05 '26 09:03 raludi

The same thing is happening.

bino98 avatar Mar 05 '26 10:03 bino98

same on my side: Debian 13 (trixie) Raspberry Pi 4B, kernel 6.12.62+rpt-rpi-v8 (aarch64).

gws version: 0.4.3

mariusCatalin avatar Mar 05 '26 14:03 mariusCatalin

Update: My previous comment was wrong. --account alone does not fix the issue. After deeper investigation, here's the full picture:

Environment

  • gws version: 0.4.4 (latest as of today)
  • OS: macOS Darwin 25.3.0, Apple Silicon
  • Installed via: brew install googleworkspace/tap/gws

Problem

gws auth login --account [email protected] completes the OAuth flow successfully and reports:

{
  "credentials_file": "~/.config/gws/credentials.<base64-account>.enc",
  "encryption": "AES-256-GCM (key secured by OS Keyring or local .encryption_key)",
  "message": "Authentication successful. Encrypted credentials saved.",
  "status": "success"
}

But every subsequent command fails with:

{
  "code": 401,
  "message": "Access denied. No credentials provided.",
  "reason": "authError"
}

gws auth status shows "auth_method": "none" and "storage": "none", meaning the CLI does not detect the encrypted credentials it just wrote.

Investigation

  • The .encryption_key file exists in ~/.config/gws/ and is valid (32 bytes, base64-encoded).
  • The .enc file is valid AES-256-GCM ciphertext (12-byte nonce + ciphertext + 16-byte auth tag).
  • Manually decrypting with Node.js crypto.createDecipheriv('aes-256-gcm', ...) produces valid JSON with client_id, client_secret, refresh_token, and type: "authorized_user".
  • The refresh token is valid. Exchanging it via curl to https://oauth2.googleapis.com/token returns a working access token.

Conclusion: The credentials and encryption are fine. The bug is in the credential reading path. gws writes encrypted credentials successfully but fails to read them back.

Workaround

Decrypt the .enc file and save it as plain-text credentials.json, which gws auto-detects:

node -e "
const c=require('crypto'),f=require('fs'),p=require('path');
const d=p.join(require('os').homedir(),'.config','gws');
const k=Buffer.from(f.readFileSync(p.join(d,'.encryption_key'),'utf8').trim(),'base64');
const enc=f.readdirSync(d).find(x=>x.endsWith('.enc'));
const data=f.readFileSync(p.join(d,enc));
const dc=c.createDecipheriv('aes-256-gcm',k,data.slice(0,12));
dc.setAuthTag(data.slice(-16));
let o=dc.update(data.slice(12,-16),null,'utf8')+dc.final('utf8');
f.writeFileSync(p.join(d,'credentials.json'),o,{mode:0o600});
console.log('Done: credentials.json written');
"

After this, all gws commands work without any env vars or flags — the CLI picks up credentials.json automatically.

What should be fixed

The encrypted credential read path is broken. It writes .enc files correctly but cannot read them back, despite the .encryption_key being present and valid. This affects v0.3.4 (#137), v0.4.3 (this issue), and v0.4.4 (my case), across macOS, Linux (comment above by @mariusCatalin), and Windows (#156).

srgfrancisco avatar Mar 05 '26 14:03 srgfrancisco

Workaround: decrypt stored credentials + manual token exchange

Hit the same issue on macOS 15.5, Apple Silicon (M4), v0.4.4. Found the root cause and submitted a fix in #196 — the CLI silently swallows credential loading errors and sends requests without auth headers.

In the meantime, here's a workaround. The real credentials are in credentials.enc (AES-256-GCM encrypted), not credentials.json (which contains truncated/masked values). You can decrypt them and exchange the refresh token for an access token:

Save as ~/.config/gws/refresh-token.sh:

#!/bin/bash
set -euo pipefail
python3 << 'PYEOF'
import base64, json, os, urllib.request, urllib.parse
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

config_dir = os.path.expanduser("~/.config/gws")

with open(os.path.join(config_dir, ".encryption_key")) as f:
    key = base64.b64decode(f.read().strip())

with open(os.path.join(config_dir, "credentials.enc"), "rb") as f:
    enc = f.read()

creds = json.loads(AESGCM(key).decrypt(enc[:12], enc[12:], None))

data = urllib.parse.urlencode({
    "client_id": creds["client_id"],
    "client_secret": creds["client_secret"],
    "refresh_token": creds["refresh_token"],
    "grant_type": "refresh_token"
}).encode()

req = urllib.request.Request("https://oauth2.googleapis.com/token", data=data, method="POST")
print(json.loads(urllib.request.urlopen(req).read())["access_token"])
PYEOF

Requires: pip install cryptography

Usage:

chmod +x ~/.config/gws/refresh-token.sh
export GOOGLE_WORKSPACE_CLI_TOKEN=$(~/.config/gws/refresh-token.sh)
gws drive files list --params '{"pageSize": 5}'  # works!

Token expires after ~1 hour. Re-run the export to refresh.

For MCP server usage (Claude Code, Cursor, etc.), auto-refresh on startup:

#!/bin/bash
export GOOGLE_WORKSPACE_CLI_TOKEN=$(~/.config/gws/refresh-token.sh)
exec gws mcp --services drive,gmail,calendar,docs,sheets,tasks --helpers --workflows

tjp2021 avatar Mar 05 '26 18:03 tjp2021

Fixed by #175 (merged), which addresses legacy credential fallback, silent auth error swallowing, and missing openid/email scopes during login.

jpoehnelt avatar Mar 05 '26 23:03 jpoehnelt