gws-cli 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gws/__init__.py +3 -0
- gws/__main__.py +9 -0
- gws/auth/__init__.py +14 -0
- gws/auth/oauth.py +211 -0
- gws/auth/provider.py +97 -0
- gws/auth/scopes.py +47 -0
- gws/auth/server.py +700 -0
- gws/cli.py +1123 -0
- gws/commands/__init__.py +1 -0
- gws/commands/_account.py +55 -0
- gws/commands/calendar.py +688 -0
- gws/commands/contacts.py +291 -0
- gws/commands/convert.py +122 -0
- gws/commands/docs.py +1432 -0
- gws/commands/drive.py +580 -0
- gws/commands/gmail.py +885 -0
- gws/commands/sheets.py +1550 -0
- gws/commands/slides.py +1107 -0
- gws/config.py +451 -0
- gws/context.py +14 -0
- gws/crypto.py +217 -0
- gws/exceptions.py +58 -0
- gws/output.py +111 -0
- gws/services/__init__.py +1 -0
- gws/services/base.py +47 -0
- gws/services/calendar.py +1377 -0
- gws/services/contacts.py +812 -0
- gws/services/convert.py +879 -0
- gws/services/docs.py +3723 -0
- gws/services/drive.py +1807 -0
- gws/services/gmail.py +2001 -0
- gws/services/sheets.py +3689 -0
- gws/services/slides.py +2845 -0
- gws/utils/__init__.py +1 -0
- gws/utils/colors.py +25 -0
- gws/utils/diagrams.py +220 -0
- gws/utils/retry.py +111 -0
- gws/utils/security.py +23 -0
- gws_cli-1.0.0.dist-info/METADATA +283 -0
- gws_cli-1.0.0.dist-info/RECORD +43 -0
- gws_cli-1.0.0.dist-info/WHEEL +4 -0
- gws_cli-1.0.0.dist-info/entry_points.txt +2 -0
- gws_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
gws/auth/server.py
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
"""Server auth provider — delegates authentication to an oauth-token-relay server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import secrets
|
|
8
|
+
import base64
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
import webbrowser
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
from urllib.parse import urlencode
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
from google.oauth2.credentials import Credentials
|
|
18
|
+
|
|
19
|
+
from gws.config import Config
|
|
20
|
+
from gws.crypto import save_encrypted, load_encrypted, delete_encrypted
|
|
21
|
+
from gws.exceptions import AuthError
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ServerAuthProvider:
|
|
25
|
+
"""Auth provider that delegates OAuth to an oauth-token-relay server.
|
|
26
|
+
|
|
27
|
+
The server handles:
|
|
28
|
+
- OAuth 2.1 authentication of the CLI user (PKCE or device flow)
|
|
29
|
+
- Provider resolution (which Google OAuth app to use)
|
|
30
|
+
- Token exchange with Google (using server-held client_secret)
|
|
31
|
+
- Token refresh via the server
|
|
32
|
+
|
|
33
|
+
The CLI holds:
|
|
34
|
+
- A server JWT (for authenticating to the relay server)
|
|
35
|
+
- Google API tokens (obtained through the relay, stored locally)
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
_LEGACY_TOKEN_PATH = Path.home() / ".config" / "gws-cli" / "token.json"
|
|
39
|
+
_SERVER_TOKEN_FILENAME = "server_token.json"
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
server_url: str,
|
|
44
|
+
account: str | None = None,
|
|
45
|
+
config: Config | None = None,
|
|
46
|
+
):
|
|
47
|
+
self.server_url = server_url.rstrip("/")
|
|
48
|
+
from gws.auth.provider import _validate_server_url
|
|
49
|
+
_validate_server_url(self.server_url)
|
|
50
|
+
self.config = config or Config.load()
|
|
51
|
+
self._account_name = self.config.resolve_account(account)
|
|
52
|
+
|
|
53
|
+
# Validate account if specified
|
|
54
|
+
if self._account_name and self.config.accounts:
|
|
55
|
+
if self._account_name not in self.config.accounts.entries:
|
|
56
|
+
raise AuthError(
|
|
57
|
+
f"Account '{self._account_name}' not found",
|
|
58
|
+
f"Available accounts: {', '.join(self.config.accounts.entries.keys())}",
|
|
59
|
+
)
|
|
60
|
+
elif self._account_name and not self.config.accounts:
|
|
61
|
+
raise AuthError(
|
|
62
|
+
f"Account '{self._account_name}' specified but no accounts are configured",
|
|
63
|
+
"Use 'gws-cli account add <name>' to set up multi-account mode.",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Load effective config for this account
|
|
67
|
+
if self._account_name:
|
|
68
|
+
self.config = self.config.load_effective_config(self._account_name)
|
|
69
|
+
|
|
70
|
+
self._credentials: Credentials | None = None
|
|
71
|
+
self._server_token: dict[str, Any] | None = None
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def account_name(self) -> str | None:
|
|
75
|
+
"""The resolved account name, or None for legacy mode."""
|
|
76
|
+
return self._account_name
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def TOKEN_PATH(self) -> Path: # noqa: N802
|
|
80
|
+
"""Path to the Google API token file (same layout as local mode)."""
|
|
81
|
+
if self._account_name:
|
|
82
|
+
return self.config.get_account_dir(self._account_name) / "token.json"
|
|
83
|
+
return self._LEGACY_TOKEN_PATH
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def _server_token_path(self) -> Path:
|
|
87
|
+
"""Path to the server JWT file."""
|
|
88
|
+
if self._account_name:
|
|
89
|
+
return self.config.get_account_dir(self._account_name) / self._SERVER_TOKEN_FILENAME
|
|
90
|
+
return Path.home() / ".config" / "gws-cli" / self._SERVER_TOKEN_FILENAME
|
|
91
|
+
|
|
92
|
+
# ── AuthProvider protocol methods ─────────────────────────────────
|
|
93
|
+
|
|
94
|
+
def get_credentials(self, force_refresh: bool = False) -> Credentials:
|
|
95
|
+
"""Get valid Google API credentials via the server relay.
|
|
96
|
+
|
|
97
|
+
Flow:
|
|
98
|
+
1. Load cached credentials from local token file
|
|
99
|
+
2. If valid and not force_refresh, return them
|
|
100
|
+
3. If expired, refresh via server (POST /auth/tokens/refresh)
|
|
101
|
+
4. If no credentials, initiate full flow via server
|
|
102
|
+
5. Save credentials locally
|
|
103
|
+
"""
|
|
104
|
+
if self._credentials and self._credentials.valid and not force_refresh:
|
|
105
|
+
return self._credentials
|
|
106
|
+
|
|
107
|
+
# Try loading existing Google token (with expiry)
|
|
108
|
+
if not force_refresh:
|
|
109
|
+
self._credentials = self._load_google_token()
|
|
110
|
+
|
|
111
|
+
# Refresh if expired
|
|
112
|
+
if self._credentials and self._credentials.expired and self._credentials.refresh_token:
|
|
113
|
+
try:
|
|
114
|
+
self._refresh_via_server(self._credentials.refresh_token)
|
|
115
|
+
return self._credentials # Set by _refresh_via_server
|
|
116
|
+
except (httpx.RequestError, httpx.HTTPStatusError, AuthError, json.JSONDecodeError, KeyError) as e:
|
|
117
|
+
import sys
|
|
118
|
+
print(f"[gws-cli] Warning: server token refresh failed: {e}", file=sys.stderr)
|
|
119
|
+
self._credentials = None
|
|
120
|
+
|
|
121
|
+
# Full flow: start → browser → complete
|
|
122
|
+
if not self._credentials or not self._credentials.valid:
|
|
123
|
+
self._run_server_auth_flow()
|
|
124
|
+
|
|
125
|
+
return self._credentials # type: ignore[return-value]
|
|
126
|
+
|
|
127
|
+
def delete_token(self) -> bool:
|
|
128
|
+
"""Delete the Google API token file (encrypted and/or plaintext)."""
|
|
129
|
+
return delete_encrypted(self.TOKEN_PATH)
|
|
130
|
+
|
|
131
|
+
def check_credentials(self) -> tuple[bool, str, Credentials | None]:
|
|
132
|
+
"""Check credentials without triggering interactive auth."""
|
|
133
|
+
# Check server connection first
|
|
134
|
+
server_token = self._load_server_token()
|
|
135
|
+
if not server_token:
|
|
136
|
+
return False, "no_server_token", None
|
|
137
|
+
|
|
138
|
+
credentials = self._load_google_token()
|
|
139
|
+
if not credentials:
|
|
140
|
+
return False, "invalid_token", None
|
|
141
|
+
|
|
142
|
+
if credentials.valid:
|
|
143
|
+
return True, "valid", credentials
|
|
144
|
+
|
|
145
|
+
if credentials.expired and credentials.refresh_token:
|
|
146
|
+
try:
|
|
147
|
+
self._refresh_via_server(credentials.refresh_token)
|
|
148
|
+
return True, "refreshed", self._credentials
|
|
149
|
+
except Exception as e:
|
|
150
|
+
return False, f"refresh_failed: {e}", None
|
|
151
|
+
|
|
152
|
+
return False, "expired_no_refresh", credentials
|
|
153
|
+
|
|
154
|
+
# ── Server authentication (CLI user → relay server) ───────────────
|
|
155
|
+
|
|
156
|
+
def server_login(self, device_flow: bool = False) -> None:
|
|
157
|
+
"""Authenticate the CLI user to the relay server.
|
|
158
|
+
|
|
159
|
+
Uses OAuth 2.1 PKCE flow (default) or device flow (for headless).
|
|
160
|
+
Stores the server JWT locally.
|
|
161
|
+
"""
|
|
162
|
+
if device_flow:
|
|
163
|
+
self._server_device_flow()
|
|
164
|
+
else:
|
|
165
|
+
self._server_pkce_flow()
|
|
166
|
+
|
|
167
|
+
def server_logout(self) -> None:
|
|
168
|
+
"""Revoke server token and delete local server_token.json."""
|
|
169
|
+
server_token = self._load_server_token()
|
|
170
|
+
if server_token:
|
|
171
|
+
# Best-effort revoke on server
|
|
172
|
+
try:
|
|
173
|
+
self._server_request(
|
|
174
|
+
"POST",
|
|
175
|
+
"/oauth/revoke",
|
|
176
|
+
json_data={"token": server_token.get("refresh_token", "")},
|
|
177
|
+
)
|
|
178
|
+
except (httpx.RequestError, httpx.HTTPStatusError, AuthError):
|
|
179
|
+
pass # Server might be unreachable; still clean up locally
|
|
180
|
+
|
|
181
|
+
delete_encrypted(self._server_token_path)
|
|
182
|
+
self._server_token = None
|
|
183
|
+
|
|
184
|
+
def server_status(self) -> dict[str, Any]:
|
|
185
|
+
"""Check server connection and authentication status."""
|
|
186
|
+
result: dict[str, Any] = {"server_url": self.server_url}
|
|
187
|
+
|
|
188
|
+
# Check server health
|
|
189
|
+
try:
|
|
190
|
+
resp = httpx.get(f"{self.server_url}/health", timeout=10)
|
|
191
|
+
health = resp.json()
|
|
192
|
+
result["server_reachable"] = True
|
|
193
|
+
result["server_status"] = health.get("status", "unknown")
|
|
194
|
+
result["providers"] = health.get("providers", [])
|
|
195
|
+
except Exception as e:
|
|
196
|
+
result["server_reachable"] = False
|
|
197
|
+
result["server_error"] = str(e)
|
|
198
|
+
return result
|
|
199
|
+
|
|
200
|
+
# Check local server token
|
|
201
|
+
server_token = self._load_server_token()
|
|
202
|
+
if server_token:
|
|
203
|
+
result["authenticated"] = True
|
|
204
|
+
result["server_token_path"] = str(self._server_token_path)
|
|
205
|
+
else:
|
|
206
|
+
result["authenticated"] = False
|
|
207
|
+
result["hint"] = "Run 'gws-cli auth server-login' to authenticate."
|
|
208
|
+
|
|
209
|
+
return result
|
|
210
|
+
|
|
211
|
+
# ── Private: server PKCE flow ─────────────────────────────────────
|
|
212
|
+
|
|
213
|
+
def _server_pkce_flow(self) -> None:
|
|
214
|
+
"""OAuth 2.1 PKCE authorization code flow against the relay server."""
|
|
215
|
+
# Generate PKCE verifier + challenge
|
|
216
|
+
verifier = secrets.token_urlsafe(64)
|
|
217
|
+
challenge = base64.urlsafe_b64encode(
|
|
218
|
+
hashlib.sha256(verifier.encode()).digest()
|
|
219
|
+
).rstrip(b"=").decode()
|
|
220
|
+
|
|
221
|
+
state = secrets.token_urlsafe(32)
|
|
222
|
+
|
|
223
|
+
# Build authorize URL
|
|
224
|
+
redirect_uri = f"{self.server_url}/oauth/cli-callback"
|
|
225
|
+
params = {
|
|
226
|
+
"response_type": "code",
|
|
227
|
+
"client_id": "cli",
|
|
228
|
+
"code_challenge": challenge,
|
|
229
|
+
"code_challenge_method": "S256",
|
|
230
|
+
"state": state,
|
|
231
|
+
"redirect_uri": redirect_uri,
|
|
232
|
+
}
|
|
233
|
+
auth_url = f"{self.server_url}/oauth/authorize?{urlencode(params)}"
|
|
234
|
+
|
|
235
|
+
print("\n" + "=" * 60, file=sys.stderr)
|
|
236
|
+
print("OAuth Token Relay Server Authentication Required", file=sys.stderr)
|
|
237
|
+
print("=" * 60, file=sys.stderr)
|
|
238
|
+
|
|
239
|
+
# Try to open browser
|
|
240
|
+
try:
|
|
241
|
+
can_open = webbrowser.get() is not None
|
|
242
|
+
except webbrowser.Error:
|
|
243
|
+
can_open = False
|
|
244
|
+
|
|
245
|
+
if can_open:
|
|
246
|
+
print(f"\nOpening browser to:\n{auth_url}\n", file=sys.stderr)
|
|
247
|
+
webbrowser.open(auth_url)
|
|
248
|
+
else:
|
|
249
|
+
print(f"\nOpen this URL in your browser:\n{auth_url}\n", file=sys.stderr)
|
|
250
|
+
|
|
251
|
+
# Poll for authorization code (server stores it when browser callback arrives)
|
|
252
|
+
print("Waiting for authorization...\n", file=sys.stderr)
|
|
253
|
+
|
|
254
|
+
code = None
|
|
255
|
+
deadline = time.monotonic() + 600 # 10 minute timeout
|
|
256
|
+
while time.monotonic() < deadline:
|
|
257
|
+
time.sleep(2)
|
|
258
|
+
|
|
259
|
+
try:
|
|
260
|
+
poll_resp = httpx.get(
|
|
261
|
+
f"{self.server_url}/oauth/cli-poll",
|
|
262
|
+
params={"state": state},
|
|
263
|
+
timeout=10,
|
|
264
|
+
)
|
|
265
|
+
except httpx.RequestError:
|
|
266
|
+
continue # Network hiccup, retry
|
|
267
|
+
|
|
268
|
+
if poll_resp.status_code == 200:
|
|
269
|
+
code = poll_resp.json().get("code")
|
|
270
|
+
break
|
|
271
|
+
elif poll_resp.status_code == 202:
|
|
272
|
+
continue # Still pending
|
|
273
|
+
else:
|
|
274
|
+
raise AuthError(
|
|
275
|
+
"Server authentication failed",
|
|
276
|
+
f"Poll error: {poll_resp.status_code} {poll_resp.text}",
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
if not code:
|
|
280
|
+
raise AuthError("Authorization timed out. Please try again.")
|
|
281
|
+
|
|
282
|
+
# Exchange code for tokens
|
|
283
|
+
resp = httpx.post(
|
|
284
|
+
f"{self.server_url}/oauth/token",
|
|
285
|
+
data={
|
|
286
|
+
"grant_type": "authorization_code",
|
|
287
|
+
"code": code,
|
|
288
|
+
"client_id": "cli",
|
|
289
|
+
"code_verifier": verifier,
|
|
290
|
+
"redirect_uri": redirect_uri,
|
|
291
|
+
},
|
|
292
|
+
timeout=30,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
if resp.status_code != 200:
|
|
296
|
+
raise AuthError(
|
|
297
|
+
"Server authentication failed",
|
|
298
|
+
f"Status {resp.status_code}: {resp.text}",
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
token_data = resp.json()
|
|
302
|
+
self._save_server_token(token_data)
|
|
303
|
+
print("\nServer authentication successful!\n", file=sys.stderr)
|
|
304
|
+
|
|
305
|
+
# ── Private: server device flow ───────────────────────────────────
|
|
306
|
+
|
|
307
|
+
def _server_device_flow(self) -> None:
|
|
308
|
+
"""OAuth 2.1 device authorization flow (for headless/SSH)."""
|
|
309
|
+
# Initiate device flow
|
|
310
|
+
resp = httpx.post(f"{self.server_url}/oauth/device", timeout=30)
|
|
311
|
+
|
|
312
|
+
if resp.status_code != 200:
|
|
313
|
+
raise AuthError(
|
|
314
|
+
"Device flow initiation failed",
|
|
315
|
+
f"Status {resp.status_code}: {resp.text}",
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
device_data = resp.json()
|
|
319
|
+
user_code = device_data["user_code"]
|
|
320
|
+
verification_uri = device_data["verification_uri"]
|
|
321
|
+
device_code = device_data["device_code"]
|
|
322
|
+
interval = device_data.get("interval", 5)
|
|
323
|
+
expires_in = device_data.get("expires_in", 300)
|
|
324
|
+
|
|
325
|
+
print("\n" + "=" * 60, file=sys.stderr)
|
|
326
|
+
print("Server Authentication (Device Flow)", file=sys.stderr)
|
|
327
|
+
print("=" * 60, file=sys.stderr)
|
|
328
|
+
print(f"\nGo to: {verification_uri}", file=sys.stderr)
|
|
329
|
+
print(f"Enter code: {user_code}\n", file=sys.stderr)
|
|
330
|
+
print("Waiting for authorization...", file=sys.stderr)
|
|
331
|
+
|
|
332
|
+
# Poll for completion
|
|
333
|
+
deadline = time.monotonic() + expires_in
|
|
334
|
+
while time.monotonic() < deadline:
|
|
335
|
+
time.sleep(interval)
|
|
336
|
+
|
|
337
|
+
resp = httpx.post(
|
|
338
|
+
f"{self.server_url}/oauth/token",
|
|
339
|
+
data={
|
|
340
|
+
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
341
|
+
"device_code": device_code,
|
|
342
|
+
},
|
|
343
|
+
timeout=30,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
if resp.status_code == 200:
|
|
347
|
+
token_data = resp.json()
|
|
348
|
+
self._save_server_token(token_data)
|
|
349
|
+
print("\nServer authentication successful!\n", file=sys.stderr)
|
|
350
|
+
return
|
|
351
|
+
|
|
352
|
+
error = resp.json().get("error", "")
|
|
353
|
+
if error == "authorization_pending":
|
|
354
|
+
continue
|
|
355
|
+
elif error == "slow_down":
|
|
356
|
+
interval += 5
|
|
357
|
+
continue
|
|
358
|
+
else:
|
|
359
|
+
raise AuthError(
|
|
360
|
+
"Device flow failed",
|
|
361
|
+
f"Error: {error} — {resp.json().get('error_description', '')}",
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
raise AuthError("Device flow timed out. Please try again.")
|
|
365
|
+
|
|
366
|
+
# ── Private: Google token relay ───────────────────────────────────
|
|
367
|
+
|
|
368
|
+
def _run_server_auth_flow(self) -> None:
|
|
369
|
+
"""Initiate upstream OAuth via the server relay.
|
|
370
|
+
|
|
371
|
+
The CLI sends full scope URLs directly — the server is scope-agnostic
|
|
372
|
+
and passes them through to the upstream provider as-is.
|
|
373
|
+
"""
|
|
374
|
+
from gws.auth.scopes import get_scopes_for_services
|
|
375
|
+
|
|
376
|
+
server_token = self._ensure_server_token()
|
|
377
|
+
scopes = get_scopes_for_services(
|
|
378
|
+
self.config.enabled_services,
|
|
379
|
+
read_only=self.config.read_only,
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
# Discover relay provider from server health endpoint
|
|
383
|
+
provider = self._discover_relay_provider()
|
|
384
|
+
|
|
385
|
+
# Start the flow — send full scope URLs, server passes them through
|
|
386
|
+
resp = self._server_request(
|
|
387
|
+
"POST",
|
|
388
|
+
"/auth/tokens/start",
|
|
389
|
+
json_data={"scopes": scopes, "provider": provider},
|
|
390
|
+
bearer_token=server_token["access_token"],
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
if resp.status_code != 200:
|
|
394
|
+
raise AuthError(
|
|
395
|
+
"Failed to start token relay",
|
|
396
|
+
f"Status {resp.status_code}: {resp.text}",
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
start_data = resp.json()
|
|
400
|
+
auth_url = start_data["auth_url"]
|
|
401
|
+
session_id = start_data["session_id"]
|
|
402
|
+
|
|
403
|
+
print("\n" + "=" * 60, file=sys.stderr)
|
|
404
|
+
account_label = f" (account: {self._account_name})" if self._account_name else ""
|
|
405
|
+
print(f"Google OAuth Authorization Required for gws-cli{account_label}", file=sys.stderr)
|
|
406
|
+
print("=" * 60, file=sys.stderr)
|
|
407
|
+
|
|
408
|
+
try:
|
|
409
|
+
can_open = webbrowser.get() is not None
|
|
410
|
+
except webbrowser.Error:
|
|
411
|
+
can_open = False
|
|
412
|
+
|
|
413
|
+
if can_open:
|
|
414
|
+
print(f"\nOpening browser to:\n{auth_url}\n", file=sys.stderr)
|
|
415
|
+
webbrowser.open(auth_url)
|
|
416
|
+
else:
|
|
417
|
+
print(f"\nOpen this URL in your browser:\n{auth_url}\n", file=sys.stderr)
|
|
418
|
+
|
|
419
|
+
print("Waiting for authorization...\n", file=sys.stderr)
|
|
420
|
+
|
|
421
|
+
# Poll for completion (server holds tokens for ~5min)
|
|
422
|
+
deadline = time.monotonic() + 300
|
|
423
|
+
while time.monotonic() < deadline:
|
|
424
|
+
time.sleep(3)
|
|
425
|
+
|
|
426
|
+
resp = self._server_request(
|
|
427
|
+
"POST",
|
|
428
|
+
"/auth/tokens/complete",
|
|
429
|
+
json_data={"session_id": session_id},
|
|
430
|
+
bearer_token=server_token["access_token"],
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
if resp.status_code == 200:
|
|
434
|
+
token_data = resp.json()
|
|
435
|
+
self._save_google_token(token_data)
|
|
436
|
+
print("Authorization successful! Token saved.\n", file=sys.stderr)
|
|
437
|
+
return
|
|
438
|
+
elif resp.status_code == 202:
|
|
439
|
+
# Still pending
|
|
440
|
+
continue
|
|
441
|
+
else:
|
|
442
|
+
raise AuthError(
|
|
443
|
+
"Token relay failed",
|
|
444
|
+
f"Status {resp.status_code}: {resp.text}",
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
raise AuthError("Authorization timed out. Please try again.")
|
|
448
|
+
|
|
449
|
+
def _refresh_via_server(self, refresh_token: str) -> None:
|
|
450
|
+
"""Refresh Google API token via the server relay."""
|
|
451
|
+
server_token = self._ensure_server_token()
|
|
452
|
+
|
|
453
|
+
resp = self._server_request(
|
|
454
|
+
"POST",
|
|
455
|
+
"/auth/tokens/refresh",
|
|
456
|
+
json_data={
|
|
457
|
+
"refresh_token": refresh_token,
|
|
458
|
+
"provider": self._discover_relay_provider(),
|
|
459
|
+
},
|
|
460
|
+
bearer_token=server_token["access_token"],
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
if resp.status_code != 200:
|
|
464
|
+
raise AuthError(
|
|
465
|
+
"Token refresh via server failed",
|
|
466
|
+
f"Status {resp.status_code}: {resp.text}",
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
token_data = resp.json()
|
|
470
|
+
self._save_google_token(token_data, refresh_token=refresh_token)
|
|
471
|
+
|
|
472
|
+
# ── Private: helpers ──────────────────────────────────────────────
|
|
473
|
+
|
|
474
|
+
def _discover_relay_provider(self) -> str:
|
|
475
|
+
"""Resolve which relay provider to use.
|
|
476
|
+
|
|
477
|
+
Priority:
|
|
478
|
+
1. Explicit config (server_provider in gws_config.json)
|
|
479
|
+
2. Auto-discover from /health if exactly one provider exists
|
|
480
|
+
3. Error with available options
|
|
481
|
+
"""
|
|
482
|
+
# Check explicit config first
|
|
483
|
+
if self.config.server_provider:
|
|
484
|
+
return self.config.server_provider
|
|
485
|
+
|
|
486
|
+
# Auto-discover from server
|
|
487
|
+
try:
|
|
488
|
+
resp = httpx.get(f"{self.server_url}/health", timeout=10)
|
|
489
|
+
health = resp.json()
|
|
490
|
+
providers = health.get("providers", [])
|
|
491
|
+
except Exception as e:
|
|
492
|
+
raise AuthError(
|
|
493
|
+
"Cannot discover relay providers",
|
|
494
|
+
f"Server health check failed: {e}",
|
|
495
|
+
)
|
|
496
|
+
|
|
497
|
+
if not providers:
|
|
498
|
+
raise AuthError("No relay providers configured on the server.")
|
|
499
|
+
|
|
500
|
+
if len(providers) == 1:
|
|
501
|
+
return providers[0]
|
|
502
|
+
|
|
503
|
+
raise AuthError(
|
|
504
|
+
"Multiple relay providers available",
|
|
505
|
+
f"Available: {', '.join(providers)}. "
|
|
506
|
+
"Set one with: gws-cli config set-mode server --url <url> --provider <name>",
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
def _server_request(
|
|
510
|
+
self,
|
|
511
|
+
method: str,
|
|
512
|
+
path: str,
|
|
513
|
+
json_data: dict[str, Any] | None = None,
|
|
514
|
+
bearer_token: str | None = None,
|
|
515
|
+
) -> httpx.Response:
|
|
516
|
+
"""Make an authenticated request to the relay server.
|
|
517
|
+
|
|
518
|
+
Automatically refreshes the server JWT on 401 and retries once.
|
|
519
|
+
"""
|
|
520
|
+
headers: dict[str, str] = {}
|
|
521
|
+
if bearer_token:
|
|
522
|
+
headers["Authorization"] = f"Bearer {bearer_token}"
|
|
523
|
+
|
|
524
|
+
resp = httpx.request(
|
|
525
|
+
method,
|
|
526
|
+
f"{self.server_url}{path}",
|
|
527
|
+
json=json_data,
|
|
528
|
+
headers=headers,
|
|
529
|
+
timeout=30,
|
|
530
|
+
)
|
|
531
|
+
|
|
532
|
+
if resp.status_code == 401 and bearer_token:
|
|
533
|
+
new_token = self._refresh_server_token()
|
|
534
|
+
if new_token:
|
|
535
|
+
headers["Authorization"] = f"Bearer {new_token}"
|
|
536
|
+
resp = httpx.request(
|
|
537
|
+
method,
|
|
538
|
+
f"{self.server_url}{path}",
|
|
539
|
+
json=json_data,
|
|
540
|
+
headers=headers,
|
|
541
|
+
timeout=30,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
return resp
|
|
545
|
+
|
|
546
|
+
def _refresh_server_token(self) -> str | None:
|
|
547
|
+
"""Refresh the server JWT using the refresh_token.
|
|
548
|
+
|
|
549
|
+
Returns the new access_token, or None if refresh failed.
|
|
550
|
+
"""
|
|
551
|
+
server_token = self._load_server_token()
|
|
552
|
+
if not server_token or not server_token.get("refresh_token"):
|
|
553
|
+
return None
|
|
554
|
+
|
|
555
|
+
try:
|
|
556
|
+
resp = httpx.post(
|
|
557
|
+
f"{self.server_url}/oauth/token",
|
|
558
|
+
data={
|
|
559
|
+
"grant_type": "refresh_token",
|
|
560
|
+
"refresh_token": server_token["refresh_token"],
|
|
561
|
+
"client_id": "cli",
|
|
562
|
+
},
|
|
563
|
+
timeout=30,
|
|
564
|
+
)
|
|
565
|
+
except httpx.RequestError:
|
|
566
|
+
return None
|
|
567
|
+
|
|
568
|
+
if resp.status_code != 200:
|
|
569
|
+
return None
|
|
570
|
+
|
|
571
|
+
new_token_data = resp.json()
|
|
572
|
+
# Preserve the refresh_token if the server didn't issue a new one
|
|
573
|
+
if "refresh_token" not in new_token_data:
|
|
574
|
+
new_token_data["refresh_token"] = server_token["refresh_token"]
|
|
575
|
+
self._save_server_token(new_token_data)
|
|
576
|
+
return new_token_data.get("access_token")
|
|
577
|
+
|
|
578
|
+
def _load_server_token(self) -> dict[str, Any] | None:
|
|
579
|
+
"""Load the server JWT from disk (encrypted or plaintext)."""
|
|
580
|
+
if self._server_token:
|
|
581
|
+
return self._server_token
|
|
582
|
+
|
|
583
|
+
self._server_token = load_encrypted(
|
|
584
|
+
self._server_token_path, self.config.get_encryption_key()
|
|
585
|
+
)
|
|
586
|
+
return self._server_token
|
|
587
|
+
|
|
588
|
+
def _save_server_token(self, token_data: dict[str, Any]) -> None:
|
|
589
|
+
"""Save server JWT to disk (encrypted if enabled)."""
|
|
590
|
+
save_encrypted(self._server_token_path, token_data, self.config.get_encryption_key())
|
|
591
|
+
self._server_token = token_data
|
|
592
|
+
|
|
593
|
+
def _ensure_server_token(self, auto_login: bool = True) -> dict[str, Any]:
|
|
594
|
+
"""Load server token, auto-triggering login if needed.
|
|
595
|
+
|
|
596
|
+
When auto_login is True (the default), missing server tokens trigger
|
|
597
|
+
the PKCE login flow automatically so the user never needs to run
|
|
598
|
+
'gws-cli auth server-login' as a separate step.
|
|
599
|
+
"""
|
|
600
|
+
token = self._load_server_token()
|
|
601
|
+
if token:
|
|
602
|
+
return token
|
|
603
|
+
|
|
604
|
+
if not auto_login:
|
|
605
|
+
raise AuthError(
|
|
606
|
+
"Not authenticated to the server",
|
|
607
|
+
"Run 'gws-cli auth server-login' first.",
|
|
608
|
+
)
|
|
609
|
+
|
|
610
|
+
# Auto-trigger server login — one fewer manual step for the user
|
|
611
|
+
print("No server token found — starting server authentication...\n", file=sys.stderr)
|
|
612
|
+
self.server_login()
|
|
613
|
+
|
|
614
|
+
token = self._load_server_token()
|
|
615
|
+
if not token:
|
|
616
|
+
raise AuthError(
|
|
617
|
+
"Server login completed but no token was saved.",
|
|
618
|
+
"Try again with 'gws-cli auth server-login'.",
|
|
619
|
+
)
|
|
620
|
+
return token
|
|
621
|
+
|
|
622
|
+
def _load_google_token(self) -> Credentials | None:
|
|
623
|
+
"""Load Google API credentials from disk with expiry support.
|
|
624
|
+
|
|
625
|
+
We don't use Credentials.from_authorized_user_file() because it doesn't
|
|
626
|
+
restore the expiry field, causing tokens to appear perpetually valid even
|
|
627
|
+
when the access token has actually expired. Instead, we read the JSON
|
|
628
|
+
directly and construct Credentials with the saved expiry.
|
|
629
|
+
"""
|
|
630
|
+
from datetime import datetime
|
|
631
|
+
|
|
632
|
+
data = load_encrypted(self.TOKEN_PATH, self.config.get_encryption_key())
|
|
633
|
+
if not data:
|
|
634
|
+
return None
|
|
635
|
+
|
|
636
|
+
token = data.get("token")
|
|
637
|
+
if not token:
|
|
638
|
+
return None
|
|
639
|
+
|
|
640
|
+
expiry = None
|
|
641
|
+
if data.get("expiry"):
|
|
642
|
+
try:
|
|
643
|
+
expiry = datetime.fromisoformat(data["expiry"])
|
|
644
|
+
except (ValueError, TypeError):
|
|
645
|
+
pass
|
|
646
|
+
if expiry is None:
|
|
647
|
+
# No saved expiry — treat as expired so refresh logic kicks in.
|
|
648
|
+
# This handles tokens saved before expiry tracking was added.
|
|
649
|
+
expiry = datetime(2000, 1, 1)
|
|
650
|
+
# google-auth uses naive UTC datetimes internally (datetime.utcnow()),
|
|
651
|
+
# so we must strip tzinfo to avoid comparison errors.
|
|
652
|
+
if expiry.tzinfo is not None:
|
|
653
|
+
expiry = expiry.replace(tzinfo=None)
|
|
654
|
+
|
|
655
|
+
return Credentials(
|
|
656
|
+
token=token,
|
|
657
|
+
refresh_token=data.get("refresh_token"),
|
|
658
|
+
token_uri=data.get("token_uri", "https://oauth2.googleapis.com/token"),
|
|
659
|
+
client_id=data.get("client_id", ""),
|
|
660
|
+
client_secret=data.get("client_secret", ""),
|
|
661
|
+
expiry=expiry,
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
def _save_google_token(
|
|
665
|
+
self,
|
|
666
|
+
token_data: dict[str, Any],
|
|
667
|
+
refresh_token: str | None = None,
|
|
668
|
+
) -> None:
|
|
669
|
+
"""Save Google API tokens with expiry as a JSON file."""
|
|
670
|
+
from datetime import datetime, timedelta, timezone
|
|
671
|
+
|
|
672
|
+
client_id = token_data.get("client_id", "server-managed")
|
|
673
|
+
resolved_refresh = token_data.get("refresh_token", refresh_token)
|
|
674
|
+
expires_in = token_data.get("expires_in", 3600)
|
|
675
|
+
# Use naive UTC to match google-auth's internal convention
|
|
676
|
+
expiry = (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).replace(tzinfo=None)
|
|
677
|
+
|
|
678
|
+
cred_data = {
|
|
679
|
+
"token": token_data["access_token"],
|
|
680
|
+
"refresh_token": resolved_refresh,
|
|
681
|
+
"token_uri": "https://oauth2.googleapis.com/token",
|
|
682
|
+
"client_id": client_id,
|
|
683
|
+
"client_secret": "", # Held by relay server, not needed locally
|
|
684
|
+
"scopes": token_data.get("scopes", []),
|
|
685
|
+
"expiry": expiry.isoformat(),
|
|
686
|
+
}
|
|
687
|
+
# Omit fields that are None (but keep expiry even if token_data had no expires_in)
|
|
688
|
+
cred_data = {k: v for k, v in cred_data.items() if v is not None}
|
|
689
|
+
|
|
690
|
+
save_encrypted(self.TOKEN_PATH, cred_data, self.config.get_encryption_key())
|
|
691
|
+
|
|
692
|
+
self._credentials = Credentials(
|
|
693
|
+
token=token_data["access_token"],
|
|
694
|
+
refresh_token=resolved_refresh,
|
|
695
|
+
token_uri="https://oauth2.googleapis.com/token",
|
|
696
|
+
client_id=client_id,
|
|
697
|
+
client_secret="",
|
|
698
|
+
expiry=expiry,
|
|
699
|
+
)
|
|
700
|
+
|