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 ADDED
@@ -0,0 +1,3 @@
1
+ """Google Workspace CLI - Unified management for Google services."""
2
+
3
+ __version__ = "1.0.0"
gws/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Entry point for python -m gws."""
2
+
3
+ import os
4
+ os.environ.setdefault("PYTHONUNBUFFERED", "1")
5
+
6
+ from gws.cli import app
7
+
8
+ if __name__ == "__main__":
9
+ app()
gws/auth/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """Authentication module for GWS CLI."""
2
+
3
+ from gws.auth.oauth import AuthManager, LocalAuthProvider
4
+ from gws.auth.provider import AuthProvider, resolve_auth_provider
5
+ from gws.auth.scopes import SCOPES, get_scopes_for_services
6
+
7
+ __all__ = [
8
+ "AuthManager",
9
+ "AuthProvider",
10
+ "LocalAuthProvider",
11
+ "SCOPES",
12
+ "get_scopes_for_services",
13
+ "resolve_auth_provider",
14
+ ]
gws/auth/oauth.py ADDED
@@ -0,0 +1,211 @@
1
+ """OAuth authentication with loopback redirect flow."""
2
+
3
+ import json
4
+ import socket
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ import google.auth.exceptions
9
+ from google.oauth2.credentials import Credentials
10
+ from google_auth_oauthlib.flow import InstalledAppFlow
11
+ from google.auth.transport.requests import Request
12
+
13
+ from gws.auth.scopes import get_scopes_for_services
14
+ from gws.config import Config
15
+ from gws.crypto import save_encrypted, load_encrypted, delete_encrypted
16
+ from gws.exceptions import AuthError
17
+
18
+
19
+ class LocalAuthProvider:
20
+ """Local OAuth authentication provider using client_secret.json.
21
+
22
+ Handles the loopback OAuth flow for users who manage their own
23
+ Google OAuth credentials locally.
24
+ """
25
+
26
+ CREDENTIALS_PATH = Path.home() / ".config" / "gws-cli" / "client_secret.json"
27
+ _LEGACY_TOKEN_PATH = Path.home() / ".config" / "gws-cli" / "token.json"
28
+ LOOPBACK_IP = "127.0.0.1"
29
+ PORT_RANGE = range(8080, 8100)
30
+
31
+ def __init__(self, config: Config | None = None, account: str | None = None):
32
+ self.config = config or Config.load()
33
+ self._account_name = self.config.resolve_account(account)
34
+
35
+ # Validate resolved account name exists in registry
36
+ if self._account_name and self.config.accounts:
37
+ if self._account_name not in self.config.accounts.entries:
38
+ raise AuthError(
39
+ f"Account '{self._account_name}' not found",
40
+ f"Available accounts: {', '.join(self.config.accounts.entries.keys())}",
41
+ )
42
+ elif self._account_name and not self.config.accounts:
43
+ raise AuthError(
44
+ f"Account '{self._account_name}' specified but no accounts are configured",
45
+ "Use 'gws-cli account add <name>' to set up multi-account mode.",
46
+ )
47
+
48
+ # Load effective config for this account
49
+ if self._account_name:
50
+ self.config = self.config.load_effective_config(self._account_name)
51
+
52
+ self._credentials: Credentials | None = None
53
+
54
+ @property
55
+ def account_name(self) -> str | None:
56
+ """The resolved account name, or None for legacy mode."""
57
+ return self._account_name
58
+
59
+ @property
60
+ def TOKEN_PATH(self) -> Path: # noqa: N802 — kept uppercase for backward compatibility
61
+ """Return account-specific or legacy token path."""
62
+ if self._account_name:
63
+ return self.config.get_account_dir(self._account_name) / "token.json"
64
+ return self._LEGACY_TOKEN_PATH
65
+
66
+ def get_credentials(self, force_refresh: bool = False) -> Credentials:
67
+ """Get valid credentials, triggering auth flow if needed."""
68
+ if self._credentials and self._credentials.valid and not force_refresh:
69
+ return self._credentials
70
+
71
+ scopes = self._get_required_scopes()
72
+
73
+ # Try loading existing token (encrypted or plaintext)
74
+ if not force_refresh:
75
+ try:
76
+ token_data = load_encrypted(self.TOKEN_PATH, self.config.get_encryption_key())
77
+ if token_data:
78
+ self._credentials = Credentials.from_authorized_user_info(
79
+ token_data,
80
+ scopes=scopes,
81
+ )
82
+ except (ValueError, KeyError) as e:
83
+ import sys
84
+ print(f"[gws-cli] Warning: failed to load token: {e}", file=sys.stderr)
85
+ self._credentials = None
86
+
87
+ # Refresh if expired
88
+ if self._credentials and self._credentials.expired and self._credentials.refresh_token:
89
+ try:
90
+ self._credentials.refresh(Request())
91
+ self._save_credentials()
92
+ return self._credentials
93
+ except (google.auth.exceptions.RefreshError, google.auth.exceptions.TransportError, OSError) as e:
94
+ import sys
95
+ print(f"[gws-cli] Warning: token refresh failed: {e}", file=sys.stderr)
96
+ self._credentials = None
97
+
98
+ # Run auth flow if no valid credentials
99
+ if not self._credentials or not self._credentials.valid:
100
+ self._run_auth_flow(scopes)
101
+
102
+ return self._credentials # type: ignore
103
+
104
+ def _get_required_scopes(self) -> list[str]:
105
+ """Get OAuth scopes for enabled services."""
106
+ return get_scopes_for_services(
107
+ self.config.enabled_services,
108
+ read_only=self.config.read_only,
109
+ )
110
+
111
+ def _find_available_port(self) -> int:
112
+ """Find an available port for OAuth callback."""
113
+ for port in self.PORT_RANGE:
114
+ try:
115
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
116
+ s.bind((self.LOOPBACK_IP, port))
117
+ return port
118
+ except OSError:
119
+ continue
120
+ raise AuthError("No available ports in range 8080-8099 for OAuth callback")
121
+
122
+ def _run_auth_flow(self, scopes: list[str]) -> None:
123
+ """Run the OAuth loopback authentication flow."""
124
+ import sys
125
+
126
+ key = self.config.get_encryption_key()
127
+ client_config = load_encrypted(self.CREDENTIALS_PATH, key)
128
+ if not client_config:
129
+ raise AuthError(
130
+ "Credentials file not found",
131
+ "Import with: gws-cli auth import-credentials <path-to-client_secret.json>",
132
+ )
133
+
134
+ port = self._find_available_port()
135
+
136
+ flow = InstalledAppFlow.from_client_config(
137
+ client_config,
138
+ scopes=scopes,
139
+ )
140
+
141
+ # Try to open browser
142
+ try:
143
+ can_open_browser = webbrowser.get() is not None
144
+ except webbrowser.Error:
145
+ can_open_browser = False
146
+
147
+ # Print header
148
+ print("\n" + "=" * 60, file=sys.stderr)
149
+ account_label = f" (account: {self._account_name})" if self._account_name else ""
150
+ print(f"Google OAuth Authorization Required for gws-cli{account_label}", file=sys.stderr)
151
+ print("=" * 60, file=sys.stderr)
152
+
153
+ # Let run_local_server handle everything including URL generation
154
+ # The authorization_prompt_message will print the URL
155
+ self._credentials = flow.run_local_server(
156
+ host=self.LOOPBACK_IP,
157
+ port=port,
158
+ open_browser=can_open_browser,
159
+ authorization_prompt_message="\n{url}\n\n" + "=" * 60 + "\nWaiting for authorization...\n",
160
+ success_message="Authorization successful! You can close this window.",
161
+ )
162
+
163
+ print("\n✓ Authorization successful! Token saved.\n", file=sys.stderr)
164
+ self._save_credentials()
165
+
166
+ def _save_credentials(self) -> None:
167
+ """Save credentials to token file (encrypted if enabled)."""
168
+ if self._credentials:
169
+ data = json.loads(self._credentials.to_json())
170
+ save_encrypted(self.TOKEN_PATH, data, self.config.get_encryption_key())
171
+
172
+ def delete_token(self) -> bool:
173
+ """Delete the token file (encrypted and/or plaintext)."""
174
+ return delete_encrypted(self.TOKEN_PATH)
175
+
176
+ def check_credentials(self) -> tuple[bool, str, Credentials | None]:
177
+ """Check credentials without triggering auth flow.
178
+
179
+ Returns:
180
+ Tuple of (is_valid, status_message, credentials_or_none)
181
+ """
182
+ scopes = self._get_required_scopes()
183
+
184
+ try:
185
+ token_data = load_encrypted(self.TOKEN_PATH, self.config.get_encryption_key())
186
+ if not token_data:
187
+ return False, "no_token", None
188
+ credentials = Credentials.from_authorized_user_info(
189
+ token_data,
190
+ scopes=scopes,
191
+ )
192
+ except Exception as e:
193
+ return False, f"invalid_token: {e}", None
194
+
195
+ if credentials.valid:
196
+ return True, "valid", credentials
197
+
198
+ if credentials.expired and credentials.refresh_token:
199
+ try:
200
+ credentials.refresh(Request())
201
+ self._credentials = credentials
202
+ self._save_credentials()
203
+ return True, "refreshed", credentials
204
+ except Exception as e:
205
+ return False, f"refresh_failed: {e}", None
206
+
207
+ return False, "expired_no_refresh", credentials
208
+
209
+
210
+ # Backward-compatibility alias — existing code that imports AuthManager keeps working.
211
+ AuthManager = LocalAuthProvider
gws/auth/provider.py ADDED
@@ -0,0 +1,97 @@
1
+ """Auth provider protocol for pluggable authentication backends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Protocol, runtime_checkable
7
+ from urllib.parse import urlparse
8
+
9
+ from google.oauth2.credentials import Credentials
10
+
11
+
12
+ @runtime_checkable
13
+ class AuthProvider(Protocol):
14
+ """Protocol for authentication providers.
15
+
16
+ LocalAuthProvider: handles OAuth locally with client_secret.json.
17
+ ServerAuthProvider: delegates to an oauth-token-relay server.
18
+ """
19
+
20
+ def get_credentials(self, force_refresh: bool = False) -> Credentials:
21
+ """Get valid Google API credentials, triggering auth if needed."""
22
+ ...
23
+
24
+ def delete_token(self) -> bool:
25
+ """Delete stored token(s). Returns True if a token was deleted."""
26
+ ...
27
+
28
+ def check_credentials(self) -> tuple[bool, str, Credentials | None]:
29
+ """Check credentials without triggering interactive auth.
30
+
31
+ Returns:
32
+ Tuple of (is_valid, status_message, credentials_or_none)
33
+ """
34
+ ...
35
+
36
+ @property
37
+ def TOKEN_PATH(self) -> Path: # noqa: N802
38
+ """Path to the token file."""
39
+ ...
40
+
41
+ @property
42
+ def account_name(self) -> str | None:
43
+ """The resolved account name, or None for legacy mode."""
44
+ ...
45
+
46
+
47
+ def _validate_server_url(url: str) -> None:
48
+ """Require HTTPS for non-localhost relay server URLs."""
49
+ from gws.exceptions import AuthError
50
+
51
+ parsed = urlparse(url)
52
+ if parsed.scheme not in ("http", "https"):
53
+ raise AuthError(f"Invalid server URL scheme: {parsed.scheme!r}")
54
+ if parsed.scheme == "http" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
55
+ raise AuthError(
56
+ f"Insecure server URL: {url!r}",
57
+ "Use HTTPS for non-localhost relay servers.",
58
+ )
59
+
60
+
61
+ def resolve_auth_provider(
62
+ account: str | None = None,
63
+ config: Any | None = None,
64
+ ) -> AuthProvider:
65
+ """Factory: return the appropriate auth provider based on config.
66
+
67
+ Each account can have its own auth mode (local or server) via per-account
68
+ config overrides. Resolution:
69
+ 1. Load global config
70
+ 2. Resolve account name (explicit > env > default)
71
+ 3. Apply per-account overrides (mode, server_url, server_provider)
72
+ 4. GWS_SERVER_URL env var overrides per-account server_url
73
+ 5. Create the appropriate provider
74
+ """
75
+ import os
76
+
77
+ from gws.config import Config
78
+
79
+ cfg = config or Config.load()
80
+ resolved_account = account or cfg.resolve_account()
81
+
82
+ # Apply per-account overrides (mode, server_url, server_provider, etc.)
83
+ effective = cfg.load_effective_config(resolved_account)
84
+
85
+ server_url = os.environ.get("GWS_SERVER_URL") or effective.server_url
86
+
87
+ if effective.mode == "server" and server_url:
88
+ _validate_server_url(server_url)
89
+ from gws.auth.server import ServerAuthProvider
90
+
91
+ return ServerAuthProvider(
92
+ server_url=server_url, account=resolved_account, config=effective,
93
+ )
94
+
95
+ from gws.auth.oauth import LocalAuthProvider
96
+
97
+ return LocalAuthProvider(config=effective, account=resolved_account)
gws/auth/scopes.py ADDED
@@ -0,0 +1,47 @@
1
+ """OAuth scope definitions per service."""
2
+
3
+ SCOPES: dict[str, list[str]] = {
4
+ "docs": ["https://www.googleapis.com/auth/documents"],
5
+ "sheets": ["https://www.googleapis.com/auth/spreadsheets"],
6
+ "slides": ["https://www.googleapis.com/auth/presentations"],
7
+ "drive": ["https://www.googleapis.com/auth/drive"],
8
+ "gmail": ["https://www.googleapis.com/auth/gmail.modify"],
9
+ "calendar": ["https://www.googleapis.com/auth/calendar"],
10
+ "contacts": [
11
+ "https://www.googleapis.com/auth/contacts",
12
+ "https://www.googleapis.com/auth/directory.readonly",
13
+ ],
14
+ "convert": [
15
+ "https://www.googleapis.com/auth/drive",
16
+ "https://www.googleapis.com/auth/documents",
17
+ "https://www.googleapis.com/auth/presentations",
18
+ ],
19
+ }
20
+
21
+ READONLY_SCOPES: dict[str, list[str]] = {
22
+ "docs": ["https://www.googleapis.com/auth/documents.readonly"],
23
+ "sheets": ["https://www.googleapis.com/auth/spreadsheets.readonly"],
24
+ "slides": ["https://www.googleapis.com/auth/presentations.readonly"],
25
+ "drive": ["https://www.googleapis.com/auth/drive.readonly"],
26
+ "gmail": ["https://www.googleapis.com/auth/gmail.readonly"],
27
+ "calendar": ["https://www.googleapis.com/auth/calendar.readonly"],
28
+ "contacts": [
29
+ "https://www.googleapis.com/auth/contacts.readonly",
30
+ "https://www.googleapis.com/auth/directory.readonly",
31
+ ],
32
+ "convert": [
33
+ "https://www.googleapis.com/auth/drive.readonly",
34
+ "https://www.googleapis.com/auth/documents.readonly",
35
+ "https://www.googleapis.com/auth/presentations.readonly",
36
+ ],
37
+ }
38
+
39
+
40
+ def get_scopes_for_services(services: list[str], read_only: bool = False) -> list[str]:
41
+ """Get combined OAuth scopes for a list of services."""
42
+ scope_map = READONLY_SCOPES if read_only else SCOPES
43
+ scopes: set[str] = set()
44
+ for service in services:
45
+ if service in scope_map:
46
+ scopes.update(scope_map[service])
47
+ return list(scopes)