@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0
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.
- package/LICENSE +21 -0
- package/README.md +353 -2
- package/README.npm.md +28 -0
- package/auth/__init__.py +1 -0
- package/auth/auth_info_middleware.py +419 -0
- package/auth/client_secrets.py +76 -0
- package/auth/credential_store.py +598 -0
- package/auth/external_oauth_provider.py +369 -0
- package/auth/gateway_identity.py +164 -0
- package/auth/google_auth.py +1550 -0
- package/auth/google_oauth_provider.py +20 -0
- package/auth/mcp_session_middleware.py +95 -0
- package/auth/oauth21_session_store.py +1332 -0
- package/auth/oauth_callback_server.py +466 -0
- package/auth/oauth_config.py +693 -0
- package/auth/oauth_proxy_config.py +122 -0
- package/auth/oauth_responses.py +230 -0
- package/auth/oauth_types.py +92 -0
- package/auth/permissions.py +330 -0
- package/auth/port_resolver.py +153 -0
- package/auth/request_identity.py +89 -0
- package/auth/scopes.py +369 -0
- package/auth/service_decorator.py +1109 -0
- package/bin/google-workspace-mcp.cjs +123 -0
- package/core/__init__.py +1 -0
- package/core/api_enablement.py +108 -0
- package/core/attachment_storage.py +496 -0
- package/core/camel_case_middleware.py +98 -0
- package/core/cli.py +161 -0
- package/core/comments.py +609 -0
- package/core/config.py +57 -0
- package/core/context.py +43 -0
- package/core/file_limits.py +632 -0
- package/core/gcs_attachment_storage.py +253 -0
- package/core/http_utils.py +339 -0
- package/core/log_formatter.py +270 -0
- package/core/portable_schema_middleware.py +67 -0
- package/core/server.py +1192 -0
- package/core/startup_ui.py +239 -0
- package/core/storage.py +23 -0
- package/core/telemetry.py +194 -0
- package/core/tool_descriptions.py +19 -0
- package/core/tool_registry.py +311 -0
- package/core/tool_tier_loader.py +197 -0
- package/core/tool_tiers.yaml +179 -0
- package/core/toolset_header_middleware.py +67 -0
- package/core/utils.py +1537 -0
- package/core/valkey_storage.py +271 -0
- package/core/warning_filters.py +19 -0
- package/fastmcp_server.py +198 -0
- package/gappsscript/README.md +512 -0
- package/gappsscript/TESTING.md +254 -0
- package/gappsscript/__init__.py +0 -0
- package/gappsscript/apps_script_tools.py +1940 -0
- package/gcalendar/__init__.py +1 -0
- package/gcalendar/calendar_helpers.py +1323 -0
- package/gcalendar/calendar_tools.py +2252 -0
- package/gchat/__init__.py +7 -0
- package/gchat/chat_helpers.py +410 -0
- package/gchat/chat_tools.py +798 -0
- package/gcontacts/__init__.py +1 -0
- package/gcontacts/contacts_helpers.py +765 -0
- package/gcontacts/contacts_tools.py +1685 -0
- package/gdocs/__init__.py +0 -0
- package/gdocs/docs_anchors.py +163 -0
- package/gdocs/docs_comments.py +89 -0
- package/gdocs/docs_helpers.py +2201 -0
- package/gdocs/docs_links.py +87 -0
- package/gdocs/docs_markdown.py +828 -0
- package/gdocs/docs_markdown_writer.py +592 -0
- package/gdocs/docs_plain_text.py +463 -0
- package/gdocs/docs_structure.py +621 -0
- package/gdocs/docs_tables.py +425 -0
- package/gdocs/docs_tools.py +3300 -0
- package/gdocs/managers/__init__.py +18 -0
- package/gdocs/managers/batch_operation_manager.py +1694 -0
- package/gdocs/managers/header_footer_manager.py +526 -0
- package/gdocs/managers/table_operation_manager.py +488 -0
- package/gdocs/managers/validation_manager.py +1504 -0
- package/gdocs/operation_schemas.py +594 -0
- package/gdrive/__init__.py +0 -0
- package/gdrive/drive_helpers.py +1738 -0
- package/gdrive/drive_tools.py +3085 -0
- package/gforms/__init__.py +3 -0
- package/gforms/forms_tools.py +575 -0
- package/gmail/__init__.py +1 -0
- package/gmail/gmail_helpers.py +2107 -0
- package/gmail/gmail_tools.py +4895 -0
- package/gmail/gmail_web_mime.py +441 -0
- package/gsearch/__init__.py +0 -0
- package/gsearch/search_tools.py +253 -0
- package/gsheets/__init__.py +31 -0
- package/gsheets/sheets_helpers.py +2236 -0
- package/gsheets/sheets_tools.py +3280 -0
- package/gslides/__init__.py +0 -0
- package/gslides/slides_digest.py +390 -0
- package/gslides/slides_helpers.py +392 -0
- package/gslides/slides_markup.py +770 -0
- package/gslides/slides_tools.py +376 -0
- package/gtasks/__init__.py +5 -0
- package/gtasks/tasks_tools.py +936 -0
- package/main.py +1170 -0
- package/package.json +43 -4
- package/pyproject.toml +173 -0
- package/uv.lock +2504 -0
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Credential Store API for Google Workspace MCP
|
|
3
|
+
|
|
4
|
+
This module provides a standardized interface for credential storage and retrieval,
|
|
5
|
+
supporting multiple backends configurable via environment variables.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from typing import List, Optional
|
|
15
|
+
from urllib.parse import quote, unquote
|
|
16
|
+
|
|
17
|
+
from google.oauth2.credentials import Credentials
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CredentialStore(ABC):
|
|
23
|
+
"""Abstract base class for credential storage."""
|
|
24
|
+
|
|
25
|
+
FILE_EXTENSION = ".json"
|
|
26
|
+
|
|
27
|
+
@abstractmethod
|
|
28
|
+
def get_credential(self, user_email: str) -> Optional[Credentials]:
|
|
29
|
+
"""
|
|
30
|
+
Get credentials for a user by email.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
user_email: User's email address
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Google Credentials object or None if not found
|
|
37
|
+
"""
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def store_credential(self, user_email: str, credentials: Credentials) -> bool:
|
|
42
|
+
"""
|
|
43
|
+
Store credentials for a user.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
user_email: User's email address
|
|
47
|
+
credentials: Google Credentials object to store
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
True if successfully stored, False otherwise
|
|
51
|
+
"""
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
@abstractmethod
|
|
55
|
+
def delete_credential(self, user_email: str) -> bool:
|
|
56
|
+
"""
|
|
57
|
+
Delete credentials for a user.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
user_email: User's email address
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
True if successfully deleted, False otherwise
|
|
64
|
+
"""
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
@abstractmethod
|
|
68
|
+
def list_users(self) -> List[str]:
|
|
69
|
+
"""
|
|
70
|
+
List all users with stored credentials.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
List of user email addresses
|
|
74
|
+
"""
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class LocalDirectoryCredentialStore(CredentialStore):
|
|
79
|
+
"""Credential store that uses local JSON files for storage."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, base_dir: Optional[str] = None):
|
|
82
|
+
"""
|
|
83
|
+
Initialize the local JSON credential store.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
base_dir: Base directory for credential files. If None, uses the directory
|
|
87
|
+
configured by environment variables in this order:
|
|
88
|
+
1. WORKSPACE_MCP_CREDENTIALS_DIR (preferred)
|
|
89
|
+
2. GOOGLE_MCP_CREDENTIALS_DIR (backward compatibility)
|
|
90
|
+
3. ~/.google_workspace_mcp/credentials (default)
|
|
91
|
+
"""
|
|
92
|
+
if base_dir is None:
|
|
93
|
+
# Check WORKSPACE_MCP_CREDENTIALS_DIR first (preferred)
|
|
94
|
+
workspace_creds_dir = os.getenv("WORKSPACE_MCP_CREDENTIALS_DIR")
|
|
95
|
+
google_creds_dir = os.getenv("GOOGLE_MCP_CREDENTIALS_DIR")
|
|
96
|
+
|
|
97
|
+
if workspace_creds_dir:
|
|
98
|
+
base_dir = os.path.expanduser(workspace_creds_dir)
|
|
99
|
+
logger.info(
|
|
100
|
+
f"Using credentials directory from WORKSPACE_MCP_CREDENTIALS_DIR: {base_dir}"
|
|
101
|
+
)
|
|
102
|
+
# Fall back to GOOGLE_MCP_CREDENTIALS_DIR for backward compatibility
|
|
103
|
+
elif google_creds_dir:
|
|
104
|
+
base_dir = os.path.expanduser(google_creds_dir)
|
|
105
|
+
logger.info(
|
|
106
|
+
f"Using credentials directory from GOOGLE_MCP_CREDENTIALS_DIR: {base_dir}"
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
home_dir = os.path.expanduser("~")
|
|
110
|
+
if home_dir and home_dir != "~":
|
|
111
|
+
base_dir = os.path.join(
|
|
112
|
+
home_dir, ".google_workspace_mcp", "credentials"
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
base_dir = os.path.join(os.getcwd(), ".credentials")
|
|
116
|
+
logger.info(f"Using default credentials directory: {base_dir}")
|
|
117
|
+
|
|
118
|
+
self.base_dir = base_dir
|
|
119
|
+
logger.info(
|
|
120
|
+
f"LocalDirectoryCredentialStore initialized with base_dir: {base_dir}"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _legacy_safe_email(user_email: str) -> str:
|
|
125
|
+
"""Return the pre-URL-encoding filename form for backward compatibility."""
|
|
126
|
+
return re.sub(r"[^a-zA-Z0-9@._-]", "_", user_email)
|
|
127
|
+
|
|
128
|
+
def _resolve_credential_path(self, filename: str) -> str:
|
|
129
|
+
"""Resolve a credential filename under base_dir and enforce containment."""
|
|
130
|
+
creds_path = os.path.join(self.base_dir, filename)
|
|
131
|
+
|
|
132
|
+
# Verify resolved path is still under base_dir
|
|
133
|
+
base_resolved = os.path.realpath(str(self.base_dir))
|
|
134
|
+
resolved = os.path.realpath(creds_path)
|
|
135
|
+
if not resolved.startswith(base_resolved + os.sep):
|
|
136
|
+
raise ValueError(f"Invalid credential path: {creds_path}")
|
|
137
|
+
|
|
138
|
+
return creds_path
|
|
139
|
+
|
|
140
|
+
def _get_credential_path(self, user_email: str) -> str:
|
|
141
|
+
"""Get the file path for a user's credentials.
|
|
142
|
+
|
|
143
|
+
URL-encodes user_email to prevent path traversal while preserving a
|
|
144
|
+
collision-free mapping from email address to filename. For backward
|
|
145
|
+
compatibility, pre-existing legacy filenames from the older regex-based
|
|
146
|
+
sanitization scheme are still discovered if the URL-encoded file does
|
|
147
|
+
not exist yet. The resolved path is validated to remain under base_dir.
|
|
148
|
+
"""
|
|
149
|
+
if not user_email or not user_email.strip():
|
|
150
|
+
raise ValueError("user_email must be a non-empty string")
|
|
151
|
+
|
|
152
|
+
if not os.path.exists(self.base_dir):
|
|
153
|
+
os.makedirs(self.base_dir, mode=0o700, exist_ok=True)
|
|
154
|
+
logger.info(f"Created credentials directory: {self.base_dir}")
|
|
155
|
+
|
|
156
|
+
safe_email = quote(user_email, safe="@._-")
|
|
157
|
+
creds_path = self._resolve_credential_path(f"{safe_email}{self.FILE_EXTENSION}")
|
|
158
|
+
|
|
159
|
+
if os.path.exists(creds_path):
|
|
160
|
+
return creds_path
|
|
161
|
+
|
|
162
|
+
legacy_safe_email = self._legacy_safe_email(user_email)
|
|
163
|
+
if legacy_safe_email != safe_email:
|
|
164
|
+
legacy_path = self._resolve_credential_path(
|
|
165
|
+
f"{legacy_safe_email}{self.FILE_EXTENSION}"
|
|
166
|
+
)
|
|
167
|
+
if os.path.exists(legacy_path):
|
|
168
|
+
logger.info(
|
|
169
|
+
"Using legacy credential filename for %s at %s",
|
|
170
|
+
user_email,
|
|
171
|
+
legacy_path,
|
|
172
|
+
)
|
|
173
|
+
return legacy_path
|
|
174
|
+
|
|
175
|
+
return creds_path
|
|
176
|
+
|
|
177
|
+
def get_credential(self, user_email: str) -> Optional[Credentials]:
|
|
178
|
+
"""Get credentials from local JSON file."""
|
|
179
|
+
creds_path = self._get_credential_path(user_email)
|
|
180
|
+
|
|
181
|
+
if not os.path.exists(creds_path):
|
|
182
|
+
logger.debug(f"No credential file found for {user_email} at {creds_path}")
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
with open(creds_path, "r") as f:
|
|
187
|
+
creds_data = json.load(f)
|
|
188
|
+
|
|
189
|
+
# Parse expiry if present
|
|
190
|
+
expiry = None
|
|
191
|
+
if creds_data.get("expiry"):
|
|
192
|
+
try:
|
|
193
|
+
expiry = datetime.fromisoformat(creds_data["expiry"])
|
|
194
|
+
# Ensure timezone-naive datetime for Google auth library compatibility
|
|
195
|
+
if expiry.tzinfo is not None:
|
|
196
|
+
expiry = expiry.replace(tzinfo=None)
|
|
197
|
+
except (ValueError, TypeError) as e:
|
|
198
|
+
logger.warning(f"Could not parse expiry time for {user_email}: {e}")
|
|
199
|
+
|
|
200
|
+
credentials = Credentials(
|
|
201
|
+
token=creds_data.get("token"),
|
|
202
|
+
refresh_token=creds_data.get("refresh_token"),
|
|
203
|
+
token_uri=creds_data.get("token_uri"),
|
|
204
|
+
client_id=creds_data.get("client_id"),
|
|
205
|
+
client_secret=creds_data.get("client_secret"),
|
|
206
|
+
scopes=creds_data.get("scopes"),
|
|
207
|
+
expiry=expiry,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
logger.debug(f"Loaded credentials for {user_email} from {creds_path}")
|
|
211
|
+
return credentials
|
|
212
|
+
|
|
213
|
+
except (IOError, json.JSONDecodeError, KeyError) as e:
|
|
214
|
+
logger.error(
|
|
215
|
+
f"Error loading credentials for {user_email} from {creds_path}: {e}"
|
|
216
|
+
)
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
def store_credential(self, user_email: str, credentials: Credentials) -> bool:
|
|
220
|
+
"""Store credentials to local JSON file."""
|
|
221
|
+
creds_path = self._get_credential_path(user_email)
|
|
222
|
+
|
|
223
|
+
creds_data = {
|
|
224
|
+
"token": credentials.token,
|
|
225
|
+
"refresh_token": credentials.refresh_token,
|
|
226
|
+
"token_uri": credentials.token_uri,
|
|
227
|
+
"client_id": credentials.client_id,
|
|
228
|
+
"client_secret": credentials.client_secret,
|
|
229
|
+
"scopes": credentials.scopes,
|
|
230
|
+
"expiry": credentials.expiry.isoformat() if credentials.expiry else None,
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
try:
|
|
234
|
+
fd = os.open(str(creds_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
235
|
+
with os.fdopen(fd, "w") as f:
|
|
236
|
+
json.dump(creds_data, f, indent=2)
|
|
237
|
+
logger.info(f"Stored credentials for {user_email} to {creds_path}")
|
|
238
|
+
return True
|
|
239
|
+
except IOError as e:
|
|
240
|
+
logger.error(
|
|
241
|
+
f"Error storing credentials for {user_email} to {creds_path}: {e}"
|
|
242
|
+
)
|
|
243
|
+
return False
|
|
244
|
+
|
|
245
|
+
def delete_credential(self, user_email: str) -> bool:
|
|
246
|
+
"""Delete credential file for a user."""
|
|
247
|
+
creds_path = self._get_credential_path(user_email)
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
if os.path.exists(creds_path):
|
|
251
|
+
os.remove(creds_path)
|
|
252
|
+
logger.info(f"Deleted credentials for {user_email} from {creds_path}")
|
|
253
|
+
return True
|
|
254
|
+
else:
|
|
255
|
+
logger.debug(
|
|
256
|
+
f"No credential file to delete for {user_email} at {creds_path}"
|
|
257
|
+
)
|
|
258
|
+
return True # Consider it a success if file doesn't exist
|
|
259
|
+
except IOError as e:
|
|
260
|
+
logger.error(
|
|
261
|
+
f"Error deleting credentials for {user_email} from {creds_path}: {e}"
|
|
262
|
+
)
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
def list_users(self) -> List[str]:
|
|
266
|
+
"""List all users with credential files."""
|
|
267
|
+
if not os.path.exists(self.base_dir):
|
|
268
|
+
return []
|
|
269
|
+
|
|
270
|
+
users = set()
|
|
271
|
+
non_credential_files = {"oauth_states"}
|
|
272
|
+
try:
|
|
273
|
+
for filename in os.listdir(self.base_dir):
|
|
274
|
+
if filename.endswith(self.FILE_EXTENSION):
|
|
275
|
+
stored_name = filename[: -len(self.FILE_EXTENSION)]
|
|
276
|
+
user_email = (
|
|
277
|
+
unquote(stored_name) if "%" in stored_name else stored_name
|
|
278
|
+
)
|
|
279
|
+
if (
|
|
280
|
+
stored_name in non_credential_files
|
|
281
|
+
or user_email in non_credential_files
|
|
282
|
+
or "@" not in user_email
|
|
283
|
+
):
|
|
284
|
+
continue
|
|
285
|
+
users.add(user_email)
|
|
286
|
+
logger.debug(
|
|
287
|
+
f"Found {len(users)} users with credentials in {self.base_dir}"
|
|
288
|
+
)
|
|
289
|
+
except OSError as e:
|
|
290
|
+
logger.error(f"Error listing credential files in {self.base_dir}: {e}")
|
|
291
|
+
|
|
292
|
+
return sorted(users)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class GCSCredentialStore(CredentialStore):
|
|
296
|
+
"""Credential store backed directly by a Google Cloud Storage bucket.
|
|
297
|
+
|
|
298
|
+
Uses the GCS JSON API (not a gcsfuse mount) which provides:
|
|
299
|
+
- Atomic read-modify-write via generation preconditions (prevents lost
|
|
300
|
+
updates on concurrent token rotation).
|
|
301
|
+
- First-class integration with Cloud IAM, Cloud Audit Logs, and VPC-SC.
|
|
302
|
+
- Transparent bucket-level CMEK encryption at rest (no app-level key).
|
|
303
|
+
|
|
304
|
+
Confidentiality at rest is delegated to the bucket's encryption
|
|
305
|
+
configuration:
|
|
306
|
+
- Default: Google-managed encryption (always on, zero configuration).
|
|
307
|
+
- CMEK: Set the bucket's default_kms_key_name (e.g. via Terraform).
|
|
308
|
+
Every object inherits the key; no per-request configuration needed.
|
|
309
|
+
|
|
310
|
+
To guard against accidentally deploying against a bucket without CMEK,
|
|
311
|
+
set ``WORKSPACE_MCP_GCS_REQUIRE_CMEK=true`` and call ``verify_cmek()``
|
|
312
|
+
during synchronous startup. Constructor initialization deliberately avoids
|
|
313
|
+
fetching bucket metadata so async callers do not block the event loop.
|
|
314
|
+
|
|
315
|
+
This backend does not support ``list_users()`` — it is designed for
|
|
316
|
+
multi-user OAuth 2.1 mode where users are looked up by email.
|
|
317
|
+
|
|
318
|
+
Configuration (env vars):
|
|
319
|
+
WORKSPACE_MCP_GCS_BUCKET — bucket name (required)
|
|
320
|
+
WORKSPACE_MCP_GCS_PREFIX — object prefix, default empty
|
|
321
|
+
WORKSPACE_MCP_GCS_REQUIRE_CMEK — "true"/"1" to enforce CMEK
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
def __init__(
|
|
325
|
+
self,
|
|
326
|
+
bucket_name: Optional[str] = None,
|
|
327
|
+
prefix: Optional[str] = None,
|
|
328
|
+
require_cmek: Optional[bool] = None,
|
|
329
|
+
):
|
|
330
|
+
from google.cloud import storage
|
|
331
|
+
from google.cloud.exceptions import NotFound, PreconditionFailed
|
|
332
|
+
|
|
333
|
+
bucket_name = bucket_name or os.getenv("WORKSPACE_MCP_GCS_BUCKET")
|
|
334
|
+
if not bucket_name:
|
|
335
|
+
raise ValueError(
|
|
336
|
+
"GCSCredentialStore requires a bucket name; "
|
|
337
|
+
"pass bucket_name or set WORKSPACE_MCP_GCS_BUCKET"
|
|
338
|
+
)
|
|
339
|
+
self.bucket_name = bucket_name
|
|
340
|
+
|
|
341
|
+
prefix = (
|
|
342
|
+
prefix if prefix is not None else os.getenv("WORKSPACE_MCP_GCS_PREFIX", "")
|
|
343
|
+
)
|
|
344
|
+
self.prefix = prefix.strip("/")
|
|
345
|
+
if self.prefix:
|
|
346
|
+
self.prefix += "/"
|
|
347
|
+
|
|
348
|
+
if require_cmek is None:
|
|
349
|
+
require_cmek = _parse_bool_env(
|
|
350
|
+
os.getenv("WORKSPACE_MCP_GCS_REQUIRE_CMEK", "")
|
|
351
|
+
)
|
|
352
|
+
self.require_cmek = require_cmek
|
|
353
|
+
|
|
354
|
+
self._NotFound = NotFound
|
|
355
|
+
self._PreconditionFailed = PreconditionFailed
|
|
356
|
+
self._client = storage.Client()
|
|
357
|
+
self._bucket = self._client.bucket(bucket_name)
|
|
358
|
+
|
|
359
|
+
logger.info(
|
|
360
|
+
f"GCSCredentialStore initialized with bucket={bucket_name}, "
|
|
361
|
+
f"prefix={self.prefix!r}, require_cmek={require_cmek}"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def _verify_cmek(self) -> None:
|
|
365
|
+
"""Fetch bucket metadata and assert a default KMS key is configured.
|
|
366
|
+
|
|
367
|
+
Raises ValueError if the bucket exists but has no default_kms_key_name.
|
|
368
|
+
Raises the underlying google exception if the bucket does not exist.
|
|
369
|
+
"""
|
|
370
|
+
self._bucket.reload()
|
|
371
|
+
if not self._bucket.default_kms_key_name:
|
|
372
|
+
raise ValueError(
|
|
373
|
+
f"GCSCredentialStore: bucket {self.bucket_name!r} has no "
|
|
374
|
+
f"default KMS key configured, but "
|
|
375
|
+
f"WORKSPACE_MCP_GCS_REQUIRE_CMEK is set. Either configure "
|
|
376
|
+
f"bucket.default_kms_key_name (e.g. via Terraform) or unset "
|
|
377
|
+
f"the requirement flag."
|
|
378
|
+
)
|
|
379
|
+
logger.info(
|
|
380
|
+
f"GCSCredentialStore: verified CMEK on bucket "
|
|
381
|
+
f"{self.bucket_name!r} (key={self._bucket.default_kms_key_name})"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def verify_cmek(self) -> None:
|
|
385
|
+
"""Synchronously verify bucket CMEK when the backend is configured to require it."""
|
|
386
|
+
if not self.require_cmek:
|
|
387
|
+
return
|
|
388
|
+
self._verify_cmek()
|
|
389
|
+
|
|
390
|
+
def _blob_name(self, user_email: str) -> str:
|
|
391
|
+
"""Construct the object key for a user, URL-encoding to prevent collisions."""
|
|
392
|
+
if not user_email or not user_email.strip():
|
|
393
|
+
raise ValueError("user_email must be a non-empty string")
|
|
394
|
+
safe_email = quote(user_email, safe="@._-")
|
|
395
|
+
return f"{self.prefix}{safe_email}{self.FILE_EXTENSION}"
|
|
396
|
+
|
|
397
|
+
def get_credential(self, user_email: str) -> Optional[Credentials]:
|
|
398
|
+
"""Download and deserialize credentials for a user."""
|
|
399
|
+
blob = self._bucket.blob(self._blob_name(user_email))
|
|
400
|
+
try:
|
|
401
|
+
raw = blob.download_as_bytes()
|
|
402
|
+
except self._NotFound:
|
|
403
|
+
logger.debug(f"No credentials object for {user_email}")
|
|
404
|
+
return None
|
|
405
|
+
except Exception as e:
|
|
406
|
+
logger.error(f"Error downloading credentials for {user_email}: {e}")
|
|
407
|
+
raise
|
|
408
|
+
|
|
409
|
+
try:
|
|
410
|
+
creds_data = json.loads(raw)
|
|
411
|
+
except json.JSONDecodeError as e:
|
|
412
|
+
logger.error(f"Error parsing credentials for {user_email}: {e}")
|
|
413
|
+
return None
|
|
414
|
+
|
|
415
|
+
expiry = None
|
|
416
|
+
if creds_data.get("expiry"):
|
|
417
|
+
try:
|
|
418
|
+
expiry = datetime.fromisoformat(creds_data["expiry"])
|
|
419
|
+
if expiry.tzinfo is not None:
|
|
420
|
+
expiry = expiry.replace(tzinfo=None)
|
|
421
|
+
except (ValueError, TypeError) as e:
|
|
422
|
+
logger.warning(f"Could not parse expiry for {user_email}: {e}")
|
|
423
|
+
|
|
424
|
+
return Credentials(
|
|
425
|
+
token=creds_data.get("token"),
|
|
426
|
+
refresh_token=creds_data.get("refresh_token"),
|
|
427
|
+
token_uri=creds_data.get("token_uri"),
|
|
428
|
+
client_id=creds_data.get("client_id"),
|
|
429
|
+
client_secret=creds_data.get("client_secret"),
|
|
430
|
+
scopes=creds_data.get("scopes"),
|
|
431
|
+
expiry=expiry,
|
|
432
|
+
)
|
|
433
|
+
|
|
434
|
+
def store_credential(self, user_email: str, credentials: Credentials) -> bool:
|
|
435
|
+
"""Serialize and upload credentials using a generation precondition.
|
|
436
|
+
|
|
437
|
+
Fails fast on concurrent writes (HTTP 412). We deliberately do NOT
|
|
438
|
+
retry: the payload we hold reflects the *pre-race* state, so
|
|
439
|
+
retrying with a fresh generation but the same payload would
|
|
440
|
+
overwrite a racing writer's updates. Returning False signals the
|
|
441
|
+
caller to abandon this attempt; the next credential refresh will
|
|
442
|
+
read the latest state and try again.
|
|
443
|
+
"""
|
|
444
|
+
creds_data = {
|
|
445
|
+
"token": credentials.token,
|
|
446
|
+
"refresh_token": credentials.refresh_token,
|
|
447
|
+
"token_uri": credentials.token_uri,
|
|
448
|
+
"client_id": credentials.client_id,
|
|
449
|
+
"client_secret": credentials.client_secret,
|
|
450
|
+
"scopes": credentials.scopes,
|
|
451
|
+
"expiry": credentials.expiry.isoformat() if credentials.expiry else None,
|
|
452
|
+
}
|
|
453
|
+
payload = json.dumps(creds_data).encode()
|
|
454
|
+
|
|
455
|
+
blob = self._bucket.blob(self._blob_name(user_email))
|
|
456
|
+
try:
|
|
457
|
+
try:
|
|
458
|
+
blob.reload()
|
|
459
|
+
generation = blob.generation
|
|
460
|
+
except self._NotFound:
|
|
461
|
+
generation = 0 # must-not-exist precondition
|
|
462
|
+
|
|
463
|
+
blob.upload_from_string(
|
|
464
|
+
payload,
|
|
465
|
+
content_type="application/json",
|
|
466
|
+
if_generation_match=generation,
|
|
467
|
+
)
|
|
468
|
+
logger.info(f"Stored credentials for {user_email}")
|
|
469
|
+
return True
|
|
470
|
+
except self._PreconditionFailed:
|
|
471
|
+
logger.warning(
|
|
472
|
+
f"Concurrent write detected for {user_email}; "
|
|
473
|
+
f"abandoning this write so next refresh can merge current state"
|
|
474
|
+
)
|
|
475
|
+
return False
|
|
476
|
+
except Exception as e:
|
|
477
|
+
logger.error(f"Error storing credentials for {user_email}: {e}")
|
|
478
|
+
return False
|
|
479
|
+
|
|
480
|
+
def delete_credential(self, user_email: str) -> bool:
|
|
481
|
+
"""Delete a user's credentials object; idempotent."""
|
|
482
|
+
blob = self._bucket.blob(self._blob_name(user_email))
|
|
483
|
+
try:
|
|
484
|
+
blob.delete()
|
|
485
|
+
logger.info(f"Deleted credentials for {user_email}")
|
|
486
|
+
return True
|
|
487
|
+
except self._NotFound:
|
|
488
|
+
return True
|
|
489
|
+
except Exception as e:
|
|
490
|
+
logger.error(f"Error deleting credentials for {user_email}: {e}")
|
|
491
|
+
return False
|
|
492
|
+
|
|
493
|
+
def list_users(self) -> List[str]:
|
|
494
|
+
"""Not supported by this backend.
|
|
495
|
+
|
|
496
|
+
Designed for multi-user OAuth 2.1 mode where users are looked up
|
|
497
|
+
individually by email. Enumerating all users requires a bucket LIST
|
|
498
|
+
which is semantically wrong for that flow. Use
|
|
499
|
+
``LocalDirectoryCredentialStore`` if you need single-user mode.
|
|
500
|
+
"""
|
|
501
|
+
raise NotImplementedError(
|
|
502
|
+
"GCSCredentialStore does not support listing users. "
|
|
503
|
+
"This backend is designed for multi-user OAuth 2.1 mode where "
|
|
504
|
+
"users are looked up individually by email. Use "
|
|
505
|
+
"LocalDirectoryCredentialStore if you need single-user mode."
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
|
|
510
|
+
_FALSE_VALUES = frozenset({"", "0", "false", "no", "off"})
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def _parse_bool_env(value: Optional[str]) -> bool:
|
|
514
|
+
"""Parse a boolean env var value, failing loudly on anything unrecognised.
|
|
515
|
+
|
|
516
|
+
Accepts (case-insensitive, whitespace-trimmed):
|
|
517
|
+
true: ``1``, ``true``, ``yes``, ``on``
|
|
518
|
+
false: ``0``, ``false``, ``no``, ``off``, empty string, None
|
|
519
|
+
|
|
520
|
+
Raises ValueError for any other input. The strict parsing matters for
|
|
521
|
+
security-relevant flags (e.g. ``WORKSPACE_MCP_GCS_REQUIRE_CMEK``) where
|
|
522
|
+
a typo like ``"treu"`` would otherwise silently disable the flag.
|
|
523
|
+
"""
|
|
524
|
+
if value is None:
|
|
525
|
+
return False
|
|
526
|
+
normalised = value.strip().lower()
|
|
527
|
+
if normalised in _TRUE_VALUES:
|
|
528
|
+
return True
|
|
529
|
+
if normalised in _FALSE_VALUES:
|
|
530
|
+
return False
|
|
531
|
+
raise ValueError(
|
|
532
|
+
f"Invalid boolean env var value: {value!r}. "
|
|
533
|
+
f"Expected one of: {sorted((_TRUE_VALUES | _FALSE_VALUES) - {''})}"
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def get_selected_backend() -> str:
|
|
538
|
+
"""Return the configured credential store backend."""
|
|
539
|
+
return (
|
|
540
|
+
os.getenv("WORKSPACE_MCP_CREDENTIAL_STORE_BACKEND", "").strip().lower()
|
|
541
|
+
or "local_directory"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _selected_backend() -> str:
|
|
546
|
+
"""Backward-compatible alias for callers not yet using the public helper."""
|
|
547
|
+
return get_selected_backend()
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
# Global credential store instance
|
|
551
|
+
_credential_store: Optional[CredentialStore] = None
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def get_credential_store() -> CredentialStore:
|
|
555
|
+
"""
|
|
556
|
+
Get the global credential store instance.
|
|
557
|
+
|
|
558
|
+
Returns:
|
|
559
|
+
Configured credential store instance
|
|
560
|
+
"""
|
|
561
|
+
global _credential_store
|
|
562
|
+
|
|
563
|
+
if _credential_store is None:
|
|
564
|
+
backend = get_selected_backend()
|
|
565
|
+
if backend == "gcs":
|
|
566
|
+
# GCS backend does not support list_users(), which is required for
|
|
567
|
+
# single-user mode. Reject unless OAuth 2.1 is enabled.
|
|
568
|
+
oauth21_enabled = _parse_bool_env(os.getenv("MCP_ENABLE_OAUTH21", "false"))
|
|
569
|
+
if not oauth21_enabled:
|
|
570
|
+
raise ValueError(
|
|
571
|
+
"GCSCredentialStore requires MCP_ENABLE_OAUTH21=true. "
|
|
572
|
+
"The GCS backend does not support list_users(), which is "
|
|
573
|
+
"required for single-user mode. Use LocalDirectoryCredentialStore "
|
|
574
|
+
"for single-user deployments, or enable OAuth 2.1 mode."
|
|
575
|
+
)
|
|
576
|
+
_credential_store = GCSCredentialStore()
|
|
577
|
+
elif backend == "local_directory":
|
|
578
|
+
_credential_store = LocalDirectoryCredentialStore()
|
|
579
|
+
else:
|
|
580
|
+
raise ValueError(
|
|
581
|
+
f"Unsupported WORKSPACE_MCP_CREDENTIAL_STORE_BACKEND: {backend!r}. "
|
|
582
|
+
f"Expected 'local_directory' or 'gcs'."
|
|
583
|
+
)
|
|
584
|
+
logger.info(f"Initialized credential store: {type(_credential_store).__name__}")
|
|
585
|
+
|
|
586
|
+
return _credential_store
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def set_credential_store(store: CredentialStore):
|
|
590
|
+
"""
|
|
591
|
+
Set the global credential store instance.
|
|
592
|
+
|
|
593
|
+
Args:
|
|
594
|
+
store: Credential store instance to use
|
|
595
|
+
"""
|
|
596
|
+
global _credential_store
|
|
597
|
+
_credential_store = store
|
|
598
|
+
logger.info(f"Set credential store: {type(store).__name__}")
|