@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.1
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 +34 -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,1550 @@
|
|
|
1
|
+
# auth/google_auth.py
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import hashlib
|
|
5
|
+
import jwt
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
import webbrowser
|
|
10
|
+
|
|
11
|
+
from collections import deque
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import List, Optional, Tuple, Dict, Any, Iterator
|
|
14
|
+
from urllib.parse import parse_qs, urlparse
|
|
15
|
+
|
|
16
|
+
from google.oauth2.credentials import Credentials
|
|
17
|
+
from google_auth_oauthlib.flow import Flow
|
|
18
|
+
from google.auth.transport.requests import Request
|
|
19
|
+
from google.auth.exceptions import RefreshError
|
|
20
|
+
import google.auth.credentials
|
|
21
|
+
from googleapiclient.discovery import Resource, build
|
|
22
|
+
from googleapiclient.errors import HttpError
|
|
23
|
+
from googleapiclient.schema import Schemas
|
|
24
|
+
import httplib2
|
|
25
|
+
import google_auth_httplib2
|
|
26
|
+
from auth.scopes import SCOPES, get_current_scopes, has_required_scopes # noqa
|
|
27
|
+
from auth.client_secrets import get_client_secrets_path, load_client_secrets_file
|
|
28
|
+
from auth.oauth21_session_store import get_oauth21_session_store
|
|
29
|
+
from auth.credential_store import CredentialStore, get_credential_store
|
|
30
|
+
from auth.gateway_identity import normalize_principal_email
|
|
31
|
+
from auth.oauth_config import (
|
|
32
|
+
is_oauth21_enabled,
|
|
33
|
+
is_stateless_mode,
|
|
34
|
+
is_trust_gateway_identity,
|
|
35
|
+
)
|
|
36
|
+
from core.config import (
|
|
37
|
+
get_transport_mode,
|
|
38
|
+
get_oauth_redirect_uri,
|
|
39
|
+
)
|
|
40
|
+
from core.context import get_fastmcp_session_id
|
|
41
|
+
|
|
42
|
+
# Try to import FastMCP dependencies (may not be available in all environments)
|
|
43
|
+
try:
|
|
44
|
+
from fastmcp.server.dependencies import get_context as get_fastmcp_context
|
|
45
|
+
except ImportError:
|
|
46
|
+
get_fastmcp_context = None
|
|
47
|
+
|
|
48
|
+
# Configure logging
|
|
49
|
+
logging.basicConfig(level=logging.INFO)
|
|
50
|
+
logger = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _session_id_log_fingerprint(session_id: Optional[str]) -> str:
|
|
54
|
+
"""Return a stable, non-reversible session identifier for logs."""
|
|
55
|
+
if not session_id:
|
|
56
|
+
return "<none>"
|
|
57
|
+
return f"sha256:{hashlib.sha256(session_id.encode()).hexdigest()[:12]}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# Constants
|
|
61
|
+
def get_default_credentials_dir():
|
|
62
|
+
"""Get the default credentials directory path, preferring user-specific locations.
|
|
63
|
+
|
|
64
|
+
Environment variable priority:
|
|
65
|
+
1. WORKSPACE_MCP_CREDENTIALS_DIR (preferred)
|
|
66
|
+
2. GOOGLE_MCP_CREDENTIALS_DIR (backward compatibility)
|
|
67
|
+
3. ~/.google_workspace_mcp/credentials (default)
|
|
68
|
+
"""
|
|
69
|
+
# Check WORKSPACE_MCP_CREDENTIALS_DIR first (preferred)
|
|
70
|
+
workspace_creds_dir = os.getenv("WORKSPACE_MCP_CREDENTIALS_DIR")
|
|
71
|
+
if workspace_creds_dir:
|
|
72
|
+
return os.path.expanduser(workspace_creds_dir)
|
|
73
|
+
|
|
74
|
+
# Fall back to GOOGLE_MCP_CREDENTIALS_DIR for backward compatibility
|
|
75
|
+
google_creds_dir = os.getenv("GOOGLE_MCP_CREDENTIALS_DIR")
|
|
76
|
+
if google_creds_dir:
|
|
77
|
+
return os.path.expanduser(google_creds_dir)
|
|
78
|
+
|
|
79
|
+
# Use user home directory for credentials storage
|
|
80
|
+
home_dir = os.path.expanduser("~")
|
|
81
|
+
if home_dir and home_dir != "~": # Valid home directory found
|
|
82
|
+
return os.path.join(home_dir, ".google_workspace_mcp", "credentials")
|
|
83
|
+
|
|
84
|
+
# Fallback to current working directory if home directory is not accessible
|
|
85
|
+
return os.path.join(os.getcwd(), ".credentials")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
DEFAULT_CREDENTIALS_DIR = get_default_credentials_dir()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
_GOOGLE_API_TIMEOUT_ENV = "WORKSPACE_MCP_GOOGLE_API_TIMEOUT_SECONDS"
|
|
92
|
+
# googleapiclient's own default socket timeout.
|
|
93
|
+
_DEFAULT_GOOGLE_API_TIMEOUT_SECONDS = 60
|
|
94
|
+
# Token validation holds one of a few dedicated workers, so it is not stretched
|
|
95
|
+
# by a timeout raised for long tool requests.
|
|
96
|
+
_USER_INFO_TIMEOUT_SECONDS = 30
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def get_google_api_timeout() -> int:
|
|
100
|
+
"""Parse WORKSPACE_MCP_GOOGLE_API_TIMEOUT_SECONDS, defaulting when unset.
|
|
101
|
+
|
|
102
|
+
Invalid values raise instead of falling back, so a misconfigured deployment
|
|
103
|
+
fails at startup.
|
|
104
|
+
"""
|
|
105
|
+
raw = os.getenv(_GOOGLE_API_TIMEOUT_ENV, "").strip()
|
|
106
|
+
if not raw:
|
|
107
|
+
return _DEFAULT_GOOGLE_API_TIMEOUT_SECONDS
|
|
108
|
+
try:
|
|
109
|
+
value = int(raw)
|
|
110
|
+
except ValueError:
|
|
111
|
+
value = 0
|
|
112
|
+
if value < 1:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"{_GOOGLE_API_TIMEOUT_ENV} must be a positive integer, got {raw!r}"
|
|
115
|
+
)
|
|
116
|
+
return value
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# httplib2 does not retry a request whose send fails on a connection the server
|
|
120
|
+
# already dropped, so only reuse connections that were active recently.
|
|
121
|
+
_HTTP_MAX_IDLE_SECONDS = 60
|
|
122
|
+
# Raw httplib2.Http objects only: they hold sockets, never credentials, so a
|
|
123
|
+
# pooled connection can safely serve any user's next request.
|
|
124
|
+
_idle_http: deque[tuple[float, httplib2.Http]] = deque(maxlen=32)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _acquire_http() -> httplib2.Http:
|
|
128
|
+
"""Pop the most recently released connection, or create a new one."""
|
|
129
|
+
try:
|
|
130
|
+
while True:
|
|
131
|
+
released_at, http = _idle_http.pop()
|
|
132
|
+
if time.monotonic() - released_at < _HTTP_MAX_IDLE_SECONDS:
|
|
133
|
+
return http
|
|
134
|
+
http.close()
|
|
135
|
+
except IndexError:
|
|
136
|
+
pass
|
|
137
|
+
http = httplib2.Http(timeout=get_google_api_timeout())
|
|
138
|
+
# Drive uses 308 Resume Incomplete with Range during resumable uploads, not a redirect.
|
|
139
|
+
http.redirect_codes = http.redirect_codes - {308}
|
|
140
|
+
return http
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _build_authorized_http(
|
|
144
|
+
credentials: google.auth.credentials.Credentials,
|
|
145
|
+
) -> google_auth_httplib2.AuthorizedHttp:
|
|
146
|
+
"""Return credentialed HTTP over a pooled, timeout-bounded connection."""
|
|
147
|
+
return google_auth_httplib2.AuthorizedHttp(credentials, http=_acquire_http())
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _no_schema_docs(*_args: Any) -> str:
|
|
151
|
+
"""Replace googleapiclient's schema pretty-printers, which feed docstrings only."""
|
|
152
|
+
return ""
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# Every client build otherwise renders the API's whole schema tree into method
|
|
156
|
+
# docstrings, tens of megabytes for Sheets and Docs.
|
|
157
|
+
Schemas.prettyPrintByName = Schemas.prettyPrintSchema = _no_schema_docs
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_google_service(
|
|
161
|
+
service_name: str, version: str, credentials: google.auth.credentials.Credentials
|
|
162
|
+
) -> Resource:
|
|
163
|
+
"""Build a discovery client on a pooled, timeout-bounded connection."""
|
|
164
|
+
return build(service_name, version, http=_build_authorized_http(credentials))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@contextmanager
|
|
168
|
+
def recycling(service: Resource) -> Iterator[Resource]:
|
|
169
|
+
"""Like contextlib.closing, but return the connection to the pool on success.
|
|
170
|
+
|
|
171
|
+
After an error or cancellation a worker thread may still be mid-request on
|
|
172
|
+
this connection, so it is closed instead and never shared with another call.
|
|
173
|
+
"""
|
|
174
|
+
try:
|
|
175
|
+
yield service
|
|
176
|
+
except BaseException:
|
|
177
|
+
service.close()
|
|
178
|
+
raise
|
|
179
|
+
_idle_http.append((time.monotonic(), service._http.http))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# Session credentials now handled by OAuth21SessionStore - no local cache needed
|
|
183
|
+
# Centralized Client Secrets Path Logic
|
|
184
|
+
CONFIG_CLIENT_SECRETS_PATH = get_client_secrets_path()
|
|
185
|
+
|
|
186
|
+
# --- Helper Functions ---
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _find_any_credentials(
|
|
190
|
+
base_dir: str = DEFAULT_CREDENTIALS_DIR,
|
|
191
|
+
) -> tuple[Optional[Credentials], Optional[str]]:
|
|
192
|
+
"""
|
|
193
|
+
Find and load any valid credentials from the credentials directory.
|
|
194
|
+
Used in single-user mode to bypass session-to-OAuth mapping.
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
Tuple of (Credentials, user_email) or (None, None) if none exist.
|
|
198
|
+
Returns the user email to enable saving refreshed credentials.
|
|
199
|
+
"""
|
|
200
|
+
try:
|
|
201
|
+
store = get_credential_store()
|
|
202
|
+
users = store.list_users()
|
|
203
|
+
if not users:
|
|
204
|
+
logger.info(
|
|
205
|
+
"[single-user] No users found with credentials via credential store"
|
|
206
|
+
)
|
|
207
|
+
return None, None
|
|
208
|
+
|
|
209
|
+
# Return credentials for the first user found
|
|
210
|
+
first_user = users[0]
|
|
211
|
+
credentials = store.get_credential(first_user)
|
|
212
|
+
if credentials:
|
|
213
|
+
logger.info(
|
|
214
|
+
f"[single-user] Found credentials for {first_user} via credential store"
|
|
215
|
+
)
|
|
216
|
+
return credentials, first_user
|
|
217
|
+
else:
|
|
218
|
+
logger.warning(
|
|
219
|
+
f"[single-user] Could not load credentials for {first_user} via credential store"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
except Exception as e:
|
|
223
|
+
logger.error(
|
|
224
|
+
f"[single-user] Error finding credentials via credential store: {e}"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
logger.info("[single-user] No valid credentials found via credential store")
|
|
228
|
+
return None, None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _stored_user_email(store: CredentialStore, user_email: str) -> str:
|
|
232
|
+
"""Return the stored spelling of user_email, matched case-insensitively."""
|
|
233
|
+
users = store.list_users()
|
|
234
|
+
if user_email in users:
|
|
235
|
+
return user_email
|
|
236
|
+
lowered = user_email.lower()
|
|
237
|
+
return next((user for user in users if user.lower() == lowered), user_email)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _id_token_email(credentials: Credentials) -> Optional[str]:
|
|
241
|
+
"""Return the email claim from the credentials' id_token, if present."""
|
|
242
|
+
if not (credentials and credentials.id_token):
|
|
243
|
+
return None
|
|
244
|
+
try:
|
|
245
|
+
return jwt.decode(
|
|
246
|
+
credentials.id_token, options={"verify_signature": False}
|
|
247
|
+
).get("email")
|
|
248
|
+
except Exception as e:
|
|
249
|
+
logger.debug(f"Could not decode id_token to get email: {e}")
|
|
250
|
+
return None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def save_credentials_to_session(session_id: str, credentials: Credentials):
|
|
254
|
+
"""Saves user credentials using OAuth21SessionStore."""
|
|
255
|
+
user_email = _id_token_email(credentials)
|
|
256
|
+
if user_email:
|
|
257
|
+
store = get_oauth21_session_store()
|
|
258
|
+
store.store_session(
|
|
259
|
+
user_email=user_email,
|
|
260
|
+
access_token=credentials.token,
|
|
261
|
+
refresh_token=credentials.refresh_token,
|
|
262
|
+
token_uri=credentials.token_uri,
|
|
263
|
+
client_id=credentials.client_id,
|
|
264
|
+
client_secret=credentials.client_secret,
|
|
265
|
+
scopes=credentials.scopes,
|
|
266
|
+
expiry=credentials.expiry,
|
|
267
|
+
mcp_session_id=session_id,
|
|
268
|
+
)
|
|
269
|
+
logger.debug(
|
|
270
|
+
f"Credentials saved to OAuth21SessionStore for session_id: {session_id}, user: {user_email}"
|
|
271
|
+
)
|
|
272
|
+
else:
|
|
273
|
+
logger.warning(
|
|
274
|
+
f"Could not save credentials to session store - no user email found for session: {session_id}"
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def load_credentials_from_session(session_id: str) -> Optional[Credentials]:
|
|
279
|
+
"""Loads user credentials from OAuth21SessionStore."""
|
|
280
|
+
store = get_oauth21_session_store()
|
|
281
|
+
credentials = store.get_credentials_by_mcp_session(session_id)
|
|
282
|
+
if credentials:
|
|
283
|
+
logger.debug(
|
|
284
|
+
f"Credentials loaded from OAuth21SessionStore for session_id: {session_id}"
|
|
285
|
+
)
|
|
286
|
+
else:
|
|
287
|
+
logger.debug(
|
|
288
|
+
f"No credentials found in OAuth21SessionStore for session_id: {session_id}"
|
|
289
|
+
)
|
|
290
|
+
return credentials
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def load_client_secrets_from_env() -> Optional[Dict[str, Any]]:
|
|
294
|
+
"""
|
|
295
|
+
Loads the client secrets from environment variables.
|
|
296
|
+
|
|
297
|
+
Environment variables used:
|
|
298
|
+
- GOOGLE_OAUTH_CLIENT_ID: OAuth client ID (required)
|
|
299
|
+
- GOOGLE_OAUTH_CLIENT_SECRET: OAuth client secret (optional for public clients)
|
|
300
|
+
- GOOGLE_OAUTH_REDIRECT_URI: (optional) OAuth redirect URI
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
Client secrets configuration dict compatible with Google OAuth library,
|
|
304
|
+
or None if required environment variables are not set.
|
|
305
|
+
"""
|
|
306
|
+
client_id = os.getenv("GOOGLE_OAUTH_CLIENT_ID")
|
|
307
|
+
client_secret = os.getenv("GOOGLE_OAUTH_CLIENT_SECRET")
|
|
308
|
+
redirect_uri = os.getenv("GOOGLE_OAUTH_REDIRECT_URI")
|
|
309
|
+
|
|
310
|
+
if client_id:
|
|
311
|
+
# Create config structure that matches Google client secrets format.
|
|
312
|
+
client_config = {
|
|
313
|
+
"client_id": client_id,
|
|
314
|
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
|
315
|
+
"token_uri": "https://oauth2.googleapis.com/token",
|
|
316
|
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
|
317
|
+
}
|
|
318
|
+
# google-auth-oauthlib token exchange expects this key to exist.
|
|
319
|
+
# Keep it as an empty string for public clients.
|
|
320
|
+
client_config["client_secret"] = client_secret or ""
|
|
321
|
+
|
|
322
|
+
# Add redirect_uri if provided via environment variable
|
|
323
|
+
if redirect_uri:
|
|
324
|
+
client_config["redirect_uris"] = [redirect_uri]
|
|
325
|
+
|
|
326
|
+
# google-auth-oauthlib supports both "web" and "installed" shapes.
|
|
327
|
+
# Use "installed" for public clients without a secret.
|
|
328
|
+
top_level_key = "web" if client_secret else "installed"
|
|
329
|
+
config = {top_level_key: client_config}
|
|
330
|
+
|
|
331
|
+
logger.info("Loaded OAuth client credentials from environment variables")
|
|
332
|
+
return config
|
|
333
|
+
|
|
334
|
+
logger.debug("OAuth client credentials not found in environment variables")
|
|
335
|
+
return None
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def load_client_secrets(client_secrets_path: str) -> Dict[str, Any]:
|
|
339
|
+
"""
|
|
340
|
+
Loads the client secrets from environment variables (preferred) or from the client secrets file.
|
|
341
|
+
|
|
342
|
+
Priority order:
|
|
343
|
+
1. Environment variables (GOOGLE_OAUTH_CLIENT_ID, GOOGLE_OAUTH_CLIENT_SECRET)
|
|
344
|
+
2. File-based credentials at the specified path
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
client_secrets_path: Path to the client secrets JSON file (used as fallback)
|
|
348
|
+
|
|
349
|
+
Returns:
|
|
350
|
+
Client secrets configuration dict
|
|
351
|
+
|
|
352
|
+
Raises:
|
|
353
|
+
ValueError: If client secrets file has invalid format
|
|
354
|
+
IOError: If file cannot be read and no environment variables are set
|
|
355
|
+
"""
|
|
356
|
+
# First, try to load from environment variables
|
|
357
|
+
env_config = load_client_secrets_from_env()
|
|
358
|
+
if env_config:
|
|
359
|
+
# Extract either "web" (confidential) or "installed" (public) config.
|
|
360
|
+
if "web" in env_config:
|
|
361
|
+
return env_config["web"]
|
|
362
|
+
if "installed" in env_config:
|
|
363
|
+
return env_config["installed"]
|
|
364
|
+
raise ValueError(
|
|
365
|
+
"Invalid environment OAuth client config format. Expected 'web' or 'installed'."
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
# Fall back to loading from file
|
|
369
|
+
try:
|
|
370
|
+
client_config = load_client_secrets_file(client_secrets_path)
|
|
371
|
+
except (IOError, ValueError) as e:
|
|
372
|
+
logger.error(f"Error loading client secrets file {client_secrets_path}: {e}")
|
|
373
|
+
raise
|
|
374
|
+
logger.info(f"Loaded OAuth client credentials from file: {client_secrets_path}")
|
|
375
|
+
return client_config
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def check_client_secrets() -> Optional[str]:
|
|
379
|
+
"""
|
|
380
|
+
Checks for the presence of OAuth client secrets, either as environment
|
|
381
|
+
variables or as a file.
|
|
382
|
+
|
|
383
|
+
Returns:
|
|
384
|
+
An error message string if secrets are not found, otherwise None.
|
|
385
|
+
"""
|
|
386
|
+
env_config = load_client_secrets_from_env()
|
|
387
|
+
if not env_config and not os.path.exists(CONFIG_CLIENT_SECRETS_PATH):
|
|
388
|
+
logger.error(
|
|
389
|
+
f"OAuth client credentials not found. No environment variables set and no file at {CONFIG_CLIENT_SECRETS_PATH}"
|
|
390
|
+
)
|
|
391
|
+
return f"OAuth client credentials not found. Please set GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET environment variables or provide a client secrets file at {CONFIG_CLIENT_SECRETS_PATH}."
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def create_oauth_flow(
|
|
396
|
+
scopes: List[str],
|
|
397
|
+
redirect_uri: str,
|
|
398
|
+
state: Optional[str] = None,
|
|
399
|
+
code_verifier: Optional[str] = None,
|
|
400
|
+
autogenerate_code_verifier: bool = True,
|
|
401
|
+
) -> Flow:
|
|
402
|
+
"""Creates an OAuth flow using environment variables or client secrets file."""
|
|
403
|
+
flow_kwargs = {
|
|
404
|
+
"scopes": scopes,
|
|
405
|
+
"redirect_uri": redirect_uri,
|
|
406
|
+
"state": state,
|
|
407
|
+
}
|
|
408
|
+
if code_verifier:
|
|
409
|
+
flow_kwargs["code_verifier"] = code_verifier
|
|
410
|
+
# Preserve the original verifier when re-creating the flow in callback.
|
|
411
|
+
flow_kwargs["autogenerate_code_verifier"] = False
|
|
412
|
+
else:
|
|
413
|
+
# Generate PKCE code verifier for the initial auth flow.
|
|
414
|
+
# google-auth-oauthlib's from_client_* helpers pass
|
|
415
|
+
# autogenerate_code_verifier=None unless explicitly provided, which
|
|
416
|
+
# prevents Flow from generating and storing a code_verifier.
|
|
417
|
+
flow_kwargs["autogenerate_code_verifier"] = autogenerate_code_verifier
|
|
418
|
+
|
|
419
|
+
# Try environment variables first
|
|
420
|
+
env_config = load_client_secrets_from_env()
|
|
421
|
+
if env_config:
|
|
422
|
+
# Use client config directly
|
|
423
|
+
flow = Flow.from_client_config(env_config, **flow_kwargs)
|
|
424
|
+
logger.debug("Created OAuth flow from environment variables")
|
|
425
|
+
return flow
|
|
426
|
+
|
|
427
|
+
# Fall back to file-based config
|
|
428
|
+
if not os.path.exists(CONFIG_CLIENT_SECRETS_PATH):
|
|
429
|
+
raise FileNotFoundError(
|
|
430
|
+
f"OAuth client secrets file not found at {CONFIG_CLIENT_SECRETS_PATH} and no environment variables set"
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
flow = Flow.from_client_secrets_file(
|
|
434
|
+
CONFIG_CLIENT_SECRETS_PATH,
|
|
435
|
+
**flow_kwargs,
|
|
436
|
+
)
|
|
437
|
+
logger.debug(
|
|
438
|
+
f"Created OAuth flow from client secrets file: {CONFIG_CLIENT_SECRETS_PATH}"
|
|
439
|
+
)
|
|
440
|
+
return flow
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _is_pkce_verifier_not_needed_error(error: Exception) -> bool:
|
|
444
|
+
"""Detect Google's legacy desktop-client response when PKCE is unnecessary."""
|
|
445
|
+
message = str(error).lower()
|
|
446
|
+
return (
|
|
447
|
+
"invalid_grant" in message
|
|
448
|
+
and "code_verifier" in message
|
|
449
|
+
and "not needed" in message
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
async def _determine_oauth_prompt(
|
|
454
|
+
user_google_email: Optional[str],
|
|
455
|
+
required_scopes: List[str],
|
|
456
|
+
session_id: Optional[str] = None,
|
|
457
|
+
) -> str:
|
|
458
|
+
"""
|
|
459
|
+
Determine which OAuth prompt to use for a new authorization URL.
|
|
460
|
+
|
|
461
|
+
Uses `select_account` for re-auth when existing credentials already cover
|
|
462
|
+
required scopes. Uses `consent` for first-time auth and scope expansion.
|
|
463
|
+
"""
|
|
464
|
+
normalized_email = (
|
|
465
|
+
user_google_email.strip()
|
|
466
|
+
if user_google_email
|
|
467
|
+
and user_google_email.strip()
|
|
468
|
+
and user_google_email.lower() != "default"
|
|
469
|
+
else None
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
# If no explicit email was provided, attempt to resolve it from session mapping.
|
|
473
|
+
if not normalized_email and session_id:
|
|
474
|
+
try:
|
|
475
|
+
session_user = get_oauth21_session_store().get_user_by_mcp_session(
|
|
476
|
+
session_id
|
|
477
|
+
)
|
|
478
|
+
if session_user:
|
|
479
|
+
normalized_email = session_user
|
|
480
|
+
except Exception as e:
|
|
481
|
+
logger.debug(f"Could not resolve user from session for prompt choice: {e}")
|
|
482
|
+
|
|
483
|
+
if not normalized_email:
|
|
484
|
+
logger.info(
|
|
485
|
+
"[start_auth_flow] Using prompt='consent' (no known user email for re-auth detection)."
|
|
486
|
+
)
|
|
487
|
+
return "consent"
|
|
488
|
+
|
|
489
|
+
existing_credentials: Optional[Credentials] = None
|
|
490
|
+
|
|
491
|
+
# Prefer credentials bound to the current session when available.
|
|
492
|
+
if session_id:
|
|
493
|
+
try:
|
|
494
|
+
session_store = get_oauth21_session_store()
|
|
495
|
+
mapped_user = session_store.get_user_by_mcp_session(session_id)
|
|
496
|
+
if mapped_user == normalized_email:
|
|
497
|
+
existing_credentials = session_store.get_credentials_by_mcp_session(
|
|
498
|
+
session_id
|
|
499
|
+
)
|
|
500
|
+
except Exception as e:
|
|
501
|
+
logger.debug(
|
|
502
|
+
f"Could not read OAuth 2.1 session store for prompt choice: {e}"
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
# Fall back to credential file store in stateful mode.
|
|
506
|
+
if not existing_credentials and not is_stateless_mode():
|
|
507
|
+
try:
|
|
508
|
+
existing_credentials = await asyncio.to_thread(
|
|
509
|
+
get_credential_store().get_credential, normalized_email
|
|
510
|
+
)
|
|
511
|
+
except Exception as e:
|
|
512
|
+
logger.debug(f"Could not read credential store for prompt choice: {e}")
|
|
513
|
+
|
|
514
|
+
if not existing_credentials:
|
|
515
|
+
logger.info(
|
|
516
|
+
f"[start_auth_flow] Using prompt='consent' (no existing credentials for {normalized_email})."
|
|
517
|
+
)
|
|
518
|
+
return "consent"
|
|
519
|
+
|
|
520
|
+
if has_required_scopes(existing_credentials.scopes, required_scopes):
|
|
521
|
+
# Verify the credentials can still be refreshed before using select_account.
|
|
522
|
+
# When credentials are revoked, Google's select_account prompt may produce
|
|
523
|
+
# incomplete callbacks (missing state parameter, partial scopes).
|
|
524
|
+
if existing_credentials.valid:
|
|
525
|
+
logger.info(
|
|
526
|
+
f"[start_auth_flow] Using prompt='select_account' for re-auth of {normalized_email}."
|
|
527
|
+
)
|
|
528
|
+
return "select_account"
|
|
529
|
+
if existing_credentials.refresh_token:
|
|
530
|
+
try:
|
|
531
|
+
await asyncio.to_thread(existing_credentials.refresh, Request())
|
|
532
|
+
logger.info(
|
|
533
|
+
f"[start_auth_flow] Using prompt='select_account' for re-auth of {normalized_email}."
|
|
534
|
+
)
|
|
535
|
+
return "select_account"
|
|
536
|
+
except Exception:
|
|
537
|
+
logger.info(
|
|
538
|
+
f"[start_auth_flow] Credentials for {normalized_email} cannot be refreshed; "
|
|
539
|
+
"using prompt='consent' to ensure full re-authorization."
|
|
540
|
+
)
|
|
541
|
+
return "consent"
|
|
542
|
+
|
|
543
|
+
logger.info(
|
|
544
|
+
f"[start_auth_flow] Using prompt='consent' (existing credentials for {normalized_email} "
|
|
545
|
+
"are not refreshable or are missing required scopes)."
|
|
546
|
+
)
|
|
547
|
+
return "consent"
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
# --- Core OAuth Logic ---
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
async def start_auth_flow(
|
|
554
|
+
user_google_email: Optional[str],
|
|
555
|
+
service_name: str, # e.g., "Google Calendar", "Gmail" for user messages
|
|
556
|
+
redirect_uri: str, # Added redirect_uri as a required parameter
|
|
557
|
+
*,
|
|
558
|
+
principal_source: Optional[str] = None,
|
|
559
|
+
) -> str:
|
|
560
|
+
"""
|
|
561
|
+
Initiates the Google OAuth flow and returns an actionable message for the user.
|
|
562
|
+
|
|
563
|
+
Args:
|
|
564
|
+
user_google_email: The user's specified Google email, if provided.
|
|
565
|
+
service_name: The name of the Google service requiring auth (for user messages).
|
|
566
|
+
redirect_uri: The URI Google will redirect to after authorization.
|
|
567
|
+
principal_source: Verified source of an enforced principal binding, if any.
|
|
568
|
+
|
|
569
|
+
Returns:
|
|
570
|
+
A formatted string containing guidance for the LLM/user.
|
|
571
|
+
|
|
572
|
+
Raises:
|
|
573
|
+
Exception: If the OAuth flow cannot be initiated.
|
|
574
|
+
"""
|
|
575
|
+
if principal_source not in (None, "gateway_assertion"):
|
|
576
|
+
raise ValueError(f"Unsupported OAuth principal source: {principal_source}")
|
|
577
|
+
|
|
578
|
+
enforce_user_email_match = principal_source == "gateway_assertion"
|
|
579
|
+
if enforce_user_email_match:
|
|
580
|
+
user_google_email = normalize_principal_email(user_google_email)
|
|
581
|
+
if not user_google_email:
|
|
582
|
+
raise GoogleAuthenticationError(
|
|
583
|
+
"Trusted-gateway OAuth flow requires a verified email principal."
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
initial_email_provided = bool(
|
|
587
|
+
user_google_email
|
|
588
|
+
and user_google_email.strip()
|
|
589
|
+
and user_google_email.lower() != "default"
|
|
590
|
+
)
|
|
591
|
+
user_display_name = (
|
|
592
|
+
f"{service_name} for '{user_google_email}'"
|
|
593
|
+
if initial_email_provided
|
|
594
|
+
else service_name
|
|
595
|
+
)
|
|
596
|
+
|
|
597
|
+
logger.info(
|
|
598
|
+
f"[start_auth_flow] Initiating auth for {user_display_name} with scopes for enabled tools."
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
# Note: Caller should ensure OAuth callback is available before calling this function
|
|
602
|
+
|
|
603
|
+
try:
|
|
604
|
+
if "OAUTHLIB_INSECURE_TRANSPORT" not in os.environ and (
|
|
605
|
+
"localhost" in redirect_uri or "127.0.0.1" in redirect_uri
|
|
606
|
+
): # Use passed redirect_uri
|
|
607
|
+
logger.warning(
|
|
608
|
+
"OAUTHLIB_INSECURE_TRANSPORT not set. Setting it for localhost/local development."
|
|
609
|
+
)
|
|
610
|
+
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
|
|
611
|
+
|
|
612
|
+
oauth_state = os.urandom(16).hex()
|
|
613
|
+
current_scopes = get_current_scopes()
|
|
614
|
+
|
|
615
|
+
flow = create_oauth_flow(
|
|
616
|
+
scopes=current_scopes, # Use scopes for enabled tools only
|
|
617
|
+
redirect_uri=redirect_uri, # Use passed redirect_uri
|
|
618
|
+
state=oauth_state,
|
|
619
|
+
)
|
|
620
|
+
|
|
621
|
+
session_id = None
|
|
622
|
+
try:
|
|
623
|
+
session_id = get_fastmcp_session_id()
|
|
624
|
+
except Exception as e:
|
|
625
|
+
logger.debug(
|
|
626
|
+
f"Could not retrieve FastMCP session ID for state binding: {e}"
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
prompt_type = await _determine_oauth_prompt(
|
|
630
|
+
user_google_email=user_google_email,
|
|
631
|
+
required_scopes=current_scopes,
|
|
632
|
+
session_id=session_id,
|
|
633
|
+
)
|
|
634
|
+
# Add login_hint if email provided so Google pre-selects the right account
|
|
635
|
+
auth_kwargs = {"access_type": "offline", "prompt": prompt_type}
|
|
636
|
+
if initial_email_provided:
|
|
637
|
+
auth_kwargs["login_hint"] = user_google_email
|
|
638
|
+
auth_url, _ = flow.authorization_url(**auth_kwargs)
|
|
639
|
+
|
|
640
|
+
browser_opened = False
|
|
641
|
+
should_open_browser = (
|
|
642
|
+
get_transport_mode() == "stdio" and not is_oauth21_enabled()
|
|
643
|
+
)
|
|
644
|
+
if should_open_browser:
|
|
645
|
+
# Only legacy stdio runs on the user's workstation. HTTP/OAuth 2.1
|
|
646
|
+
# deployments may be remote, so opening a server-side browser is wrong.
|
|
647
|
+
try:
|
|
648
|
+
browser_opened = await asyncio.to_thread(webbrowser.open, auth_url)
|
|
649
|
+
if browser_opened:
|
|
650
|
+
logger.info("Opened auth URL in browser automatically")
|
|
651
|
+
else:
|
|
652
|
+
logger.info(
|
|
653
|
+
"webbrowser.open() reported failure (likely headless environment); "
|
|
654
|
+
"falling back to displaying URL"
|
|
655
|
+
)
|
|
656
|
+
except Exception as e:
|
|
657
|
+
logger.warning(f"Could not open browser automatically: {e}")
|
|
658
|
+
|
|
659
|
+
store = get_oauth21_session_store()
|
|
660
|
+
store.store_oauth_state(
|
|
661
|
+
oauth_state,
|
|
662
|
+
session_id=session_id,
|
|
663
|
+
code_verifier=flow.code_verifier,
|
|
664
|
+
expected_user_email=(
|
|
665
|
+
user_google_email if enforce_user_email_match else None
|
|
666
|
+
),
|
|
667
|
+
enforce_user_email_match=enforce_user_email_match,
|
|
668
|
+
principal_source=principal_source,
|
|
669
|
+
)
|
|
670
|
+
|
|
671
|
+
logger.info(
|
|
672
|
+
f"Auth flow started for {user_display_name}. State: {oauth_state[:8]}... "
|
|
673
|
+
f"Browser opened automatically: {browser_opened}"
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
# Trusted-gateway identity: the principal is verified and fixed, so give a clear,
|
|
677
|
+
# identity-specific instruction — no "tell me your email" step, no generic
|
|
678
|
+
# "must match" footnote that confuses the client.
|
|
679
|
+
if enforce_user_email_match:
|
|
680
|
+
return "\n".join(
|
|
681
|
+
[
|
|
682
|
+
f"**ACTION REQUIRED: Google sign-in needed for {user_display_name}**\n",
|
|
683
|
+
f"You're authenticated at the gateway as **{user_google_email}**. To authorize Google access:",
|
|
684
|
+
f"1. Open this URL and sign in to Google as **{user_google_email}** — it must be that exact account (your verified gateway identity):",
|
|
685
|
+
f" Authorization URL: {auth_url}",
|
|
686
|
+
"2. After authorizing, retry your original request.",
|
|
687
|
+
f"\nOnly the Google account matching your gateway identity (**{user_google_email}**) can be authorized — signing in with a different account is rejected.",
|
|
688
|
+
]
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
if browser_opened:
|
|
692
|
+
message_lines = [
|
|
693
|
+
f"**ACTION REQUIRED: Google Authentication Needed for {user_display_name}**\n",
|
|
694
|
+
"1. The authorization page has been **automatically opened in your browser**. Please complete the authorization there.",
|
|
695
|
+
" If it did not appear, open this URL manually:",
|
|
696
|
+
f" Authorization URL: {auth_url}",
|
|
697
|
+
]
|
|
698
|
+
else:
|
|
699
|
+
message_lines = [
|
|
700
|
+
f"**ACTION REQUIRED: Google Authentication Needed for {user_display_name}**\n",
|
|
701
|
+
f"1. Open this URL in your browser to authorize {service_name} access using all required permissions:",
|
|
702
|
+
f" Authorization URL: {auth_url}",
|
|
703
|
+
]
|
|
704
|
+
session_info_for_llm = ""
|
|
705
|
+
|
|
706
|
+
if not initial_email_provided:
|
|
707
|
+
message_lines.extend(
|
|
708
|
+
[
|
|
709
|
+
f"2. After successful authorization{session_info_for_llm}, the browser page will display the authenticated email address.",
|
|
710
|
+
" **LLM: Instruct the user to provide you with this email address.**",
|
|
711
|
+
"3. Once you have the email, **retry their original command, ensuring you include this `user_google_email`.**",
|
|
712
|
+
]
|
|
713
|
+
)
|
|
714
|
+
else:
|
|
715
|
+
message_lines.append(
|
|
716
|
+
f"2. After successful authorization{session_info_for_llm}, **retry their original command**."
|
|
717
|
+
)
|
|
718
|
+
|
|
719
|
+
message_lines.append(
|
|
720
|
+
f"\nThe application will use the new credentials. If '{user_google_email}' was provided, it must match the authenticated account."
|
|
721
|
+
)
|
|
722
|
+
return "\n".join(message_lines)
|
|
723
|
+
|
|
724
|
+
except FileNotFoundError as e:
|
|
725
|
+
error_text = f"OAuth client credentials not found: {e}. Please either:\n1. Set environment variables: GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET\n2. Ensure '{CONFIG_CLIENT_SECRETS_PATH}' file exists"
|
|
726
|
+
logger.error(error_text, exc_info=True)
|
|
727
|
+
raise Exception(error_text)
|
|
728
|
+
except Exception as e:
|
|
729
|
+
error_text = f"Could not initiate authentication for {user_display_name} due to an unexpected error: {str(e)}"
|
|
730
|
+
logger.error(
|
|
731
|
+
f"Failed to start the OAuth flow for {user_display_name}: {e}",
|
|
732
|
+
exc_info=True,
|
|
733
|
+
)
|
|
734
|
+
raise Exception(error_text)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
async def handle_auth_callback(
|
|
738
|
+
scopes: List[str],
|
|
739
|
+
authorization_response: str,
|
|
740
|
+
redirect_uri: str,
|
|
741
|
+
credentials_base_dir: str = DEFAULT_CREDENTIALS_DIR,
|
|
742
|
+
session_id: Optional[str] = None,
|
|
743
|
+
*,
|
|
744
|
+
allow_missing_state_fallback: bool = False,
|
|
745
|
+
client_secrets_path: Optional[
|
|
746
|
+
str
|
|
747
|
+
] = None, # Deprecated: kept for backward compatibility
|
|
748
|
+
) -> Tuple[str, Credentials]:
|
|
749
|
+
"""
|
|
750
|
+
Handles the callback from Google, exchanges the code for credentials,
|
|
751
|
+
fetches user info, determines user_google_email, saves credentials (file & session),
|
|
752
|
+
and returns them.
|
|
753
|
+
|
|
754
|
+
Args:
|
|
755
|
+
scopes: List of OAuth scopes requested.
|
|
756
|
+
authorization_response: The full callback URL from Google.
|
|
757
|
+
redirect_uri: The redirect URI.
|
|
758
|
+
credentials_base_dir: Base directory for credential files.
|
|
759
|
+
session_id: Optional MCP session ID to associate with the credentials.
|
|
760
|
+
allow_missing_state_fallback: Whether to recover a missing callback state
|
|
761
|
+
from the most recently stored OAuth state. Only enable for local stdio
|
|
762
|
+
callbacks where there is no multi-user session context.
|
|
763
|
+
client_secrets_path: (Deprecated) Path to client secrets file. Ignored if environment variables are set.
|
|
764
|
+
|
|
765
|
+
Returns:
|
|
766
|
+
A tuple containing the user_google_email and the obtained Credentials object.
|
|
767
|
+
|
|
768
|
+
Raises:
|
|
769
|
+
ValueError: If the state is missing or doesn't match.
|
|
770
|
+
FlowExchangeError: If the code exchange fails.
|
|
771
|
+
HttpError: If fetching user info fails.
|
|
772
|
+
"""
|
|
773
|
+
try:
|
|
774
|
+
# Log deprecation warning if old parameter is used
|
|
775
|
+
if client_secrets_path:
|
|
776
|
+
logger.warning(
|
|
777
|
+
"The 'client_secrets_path' parameter is deprecated. Use GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET environment variables instead."
|
|
778
|
+
)
|
|
779
|
+
|
|
780
|
+
# Allow HTTP for localhost in development
|
|
781
|
+
if "OAUTHLIB_INSECURE_TRANSPORT" not in os.environ:
|
|
782
|
+
logger.warning(
|
|
783
|
+
"OAUTHLIB_INSECURE_TRANSPORT not set. Setting it for localhost development."
|
|
784
|
+
)
|
|
785
|
+
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
|
|
786
|
+
|
|
787
|
+
# Allow partial scope grants without raising an exception.
|
|
788
|
+
# When users decline some scopes on Google's consent screen,
|
|
789
|
+
# oauthlib raises because the granted scopes differ from requested.
|
|
790
|
+
if "OAUTHLIB_RELAX_TOKEN_SCOPE" not in os.environ:
|
|
791
|
+
os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"
|
|
792
|
+
|
|
793
|
+
store = get_oauth21_session_store()
|
|
794
|
+
parsed_response = urlparse(authorization_response)
|
|
795
|
+
state_values = parse_qs(parsed_response.query).get("state")
|
|
796
|
+
state = state_values[0] if state_values else None
|
|
797
|
+
|
|
798
|
+
if state:
|
|
799
|
+
state_info = store.validate_and_consume_oauth_state(
|
|
800
|
+
state, session_id=session_id
|
|
801
|
+
)
|
|
802
|
+
elif (
|
|
803
|
+
allow_missing_state_fallback
|
|
804
|
+
and os.getenv("MCP_SINGLE_USER_MODE") == "1"
|
|
805
|
+
and session_id is None
|
|
806
|
+
):
|
|
807
|
+
# stdio mode fallback: state may be absent from Google's redirect
|
|
808
|
+
# (e.g. when prompt=select_account is used with revoked credentials).
|
|
809
|
+
# Use the most recently stored state to recover the PKCE code_verifier.
|
|
810
|
+
logger.warning(
|
|
811
|
+
"OAuth callback missing state parameter; using most recent stored state (single-user stdio fallback)"
|
|
812
|
+
)
|
|
813
|
+
state_info = store.consume_latest_oauth_state(
|
|
814
|
+
initiating_session_id=session_id,
|
|
815
|
+
allow_any_session=True,
|
|
816
|
+
)
|
|
817
|
+
if not state_info:
|
|
818
|
+
raise ValueError(
|
|
819
|
+
"Missing OAuth state parameter and no stored state available"
|
|
820
|
+
)
|
|
821
|
+
else:
|
|
822
|
+
raise ValueError("Missing OAuth state parameter")
|
|
823
|
+
|
|
824
|
+
logger.debug(
|
|
825
|
+
"OAuth callback state %s for session %s",
|
|
826
|
+
(state[:8] if state else "<fallback>"),
|
|
827
|
+
state_info.get("session_id") or "<unknown>",
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
if not session_id:
|
|
831
|
+
originating_session_id = state_info.get("session_id")
|
|
832
|
+
if originating_session_id:
|
|
833
|
+
session_id = originating_session_id
|
|
834
|
+
logger.info(
|
|
835
|
+
"OAuth callback: bound credentials to originating MCP session %s",
|
|
836
|
+
_session_id_log_fingerprint(originating_session_id),
|
|
837
|
+
)
|
|
838
|
+
|
|
839
|
+
flow = create_oauth_flow(
|
|
840
|
+
scopes=scopes,
|
|
841
|
+
redirect_uri=redirect_uri,
|
|
842
|
+
state=state,
|
|
843
|
+
code_verifier=state_info.get("code_verifier"),
|
|
844
|
+
autogenerate_code_verifier=False,
|
|
845
|
+
)
|
|
846
|
+
|
|
847
|
+
# Exchange the authorization code for credentials
|
|
848
|
+
# Note: fetch_token will use the redirect_uri configured in the flow
|
|
849
|
+
try:
|
|
850
|
+
await asyncio.to_thread(
|
|
851
|
+
flow.fetch_token, authorization_response=authorization_response
|
|
852
|
+
)
|
|
853
|
+
credentials = flow.credentials
|
|
854
|
+
except Exception as exc:
|
|
855
|
+
if _is_pkce_verifier_not_needed_error(exc):
|
|
856
|
+
logger.error(
|
|
857
|
+
"OAuth token exchange rejected PKCE verifier. "
|
|
858
|
+
"The authorization code has been consumed and cannot be reused. "
|
|
859
|
+
"Please restart the authentication flow from the beginning."
|
|
860
|
+
)
|
|
861
|
+
raise
|
|
862
|
+
logger.info("Successfully exchanged authorization code for tokens.")
|
|
863
|
+
|
|
864
|
+
# Handle partial OAuth grants: if the user declined some scopes on
|
|
865
|
+
# Google's consent screen, credentials.granted_scopes contains only
|
|
866
|
+
# what was actually authorized. Store those instead of the inflated
|
|
867
|
+
# requested scopes so that refresh() sends the correct scope set.
|
|
868
|
+
granted = getattr(credentials, "granted_scopes", None)
|
|
869
|
+
if granted and set(granted) != set(credentials.scopes or []):
|
|
870
|
+
logger.warning(
|
|
871
|
+
"Partial OAuth grant detected. Requested: %s, Granted: %s",
|
|
872
|
+
credentials.scopes,
|
|
873
|
+
granted,
|
|
874
|
+
)
|
|
875
|
+
credentials = Credentials(
|
|
876
|
+
token=credentials.token,
|
|
877
|
+
refresh_token=credentials.refresh_token,
|
|
878
|
+
id_token=getattr(credentials, "id_token", None),
|
|
879
|
+
token_uri=credentials.token_uri,
|
|
880
|
+
client_id=credentials.client_id,
|
|
881
|
+
client_secret=credentials.client_secret,
|
|
882
|
+
scopes=list(granted),
|
|
883
|
+
expiry=credentials.expiry,
|
|
884
|
+
quota_project_id=getattr(credentials, "quota_project_id", None),
|
|
885
|
+
)
|
|
886
|
+
|
|
887
|
+
# Get user info to determine user_id (using email here)
|
|
888
|
+
user_info = await asyncio.to_thread(get_user_info, credentials)
|
|
889
|
+
if not user_info or "email" not in user_info:
|
|
890
|
+
logger.error("Could not retrieve user email from Google.")
|
|
891
|
+
raise ValueError("Failed to get user email for identification.")
|
|
892
|
+
|
|
893
|
+
user_google_email = user_info["email"]
|
|
894
|
+
logger.info(f"Identified user_google_email: {user_google_email}")
|
|
895
|
+
|
|
896
|
+
enforcement_marker = state_info.get("enforce_user_email_match")
|
|
897
|
+
if is_trust_gateway_identity():
|
|
898
|
+
if enforcement_marker is not True:
|
|
899
|
+
raise GoogleAuthenticationError(
|
|
900
|
+
"OAuth consent state predates trusted-gateway principal binding. "
|
|
901
|
+
"Please restart authentication."
|
|
902
|
+
)
|
|
903
|
+
elif enforcement_marker not in (True, False):
|
|
904
|
+
# State entries created before explicit binding markers existed are not
|
|
905
|
+
# enforcing outside trusted-gateway mode.
|
|
906
|
+
enforcement_marker = False
|
|
907
|
+
if enforcement_marker is True:
|
|
908
|
+
# Normalization is confined to the enforced gateway path so legacy flows
|
|
909
|
+
# keep Google's email byte-for-byte as the credential key.
|
|
910
|
+
expected_email = normalize_principal_email(
|
|
911
|
+
state_info.get("expected_user_email")
|
|
912
|
+
)
|
|
913
|
+
principal_source = state_info.get("principal_source")
|
|
914
|
+
if principal_source != "gateway_assertion" or not expected_email:
|
|
915
|
+
logger.error(
|
|
916
|
+
"SECURITY: OAuth state requires principal enforcement but its "
|
|
917
|
+
"gateway binding is missing or invalid; rejecting."
|
|
918
|
+
)
|
|
919
|
+
raise GoogleAuthenticationError(
|
|
920
|
+
"OAuth consent state is missing its verified gateway principal."
|
|
921
|
+
)
|
|
922
|
+
consented_email = normalize_principal_email(user_google_email)
|
|
923
|
+
if consented_email != expected_email:
|
|
924
|
+
logger.error(
|
|
925
|
+
"SECURITY: OAuth consent account '%s' does not match the gateway "
|
|
926
|
+
"identity '%s'; rejecting (no credentials stored).",
|
|
927
|
+
user_google_email,
|
|
928
|
+
expected_email,
|
|
929
|
+
)
|
|
930
|
+
raise GoogleAuthenticationError(
|
|
931
|
+
f"Google account mismatch: you signed in as {user_google_email}, "
|
|
932
|
+
f"but your verified gateway identity is {expected_email}. Please "
|
|
933
|
+
f"sign in to Google as {expected_email}."
|
|
934
|
+
)
|
|
935
|
+
# Use the exact canonical key selected by the gateway for every store.
|
|
936
|
+
user_google_email = expected_email
|
|
937
|
+
|
|
938
|
+
stateless_mode = is_stateless_mode()
|
|
939
|
+
credential_store = None
|
|
940
|
+
if not stateless_mode:
|
|
941
|
+
credential_store = get_credential_store()
|
|
942
|
+
if not credentials.refresh_token:
|
|
943
|
+
fallback_refresh_token = None
|
|
944
|
+
|
|
945
|
+
if session_id:
|
|
946
|
+
try:
|
|
947
|
+
session_credentials = store.get_credentials(user_google_email)
|
|
948
|
+
if session_credentials and session_credentials.refresh_token:
|
|
949
|
+
fallback_refresh_token = session_credentials.refresh_token
|
|
950
|
+
logger.info(
|
|
951
|
+
"OAuth callback response omitted refresh token; preserving existing refresh token from session store."
|
|
952
|
+
)
|
|
953
|
+
except Exception as e:
|
|
954
|
+
logger.debug(
|
|
955
|
+
f"Could not check session store for existing refresh token: {e}"
|
|
956
|
+
)
|
|
957
|
+
|
|
958
|
+
if not fallback_refresh_token and not stateless_mode:
|
|
959
|
+
try:
|
|
960
|
+
existing_credentials = await asyncio.to_thread(
|
|
961
|
+
credential_store.get_credential, user_google_email
|
|
962
|
+
)
|
|
963
|
+
if existing_credentials and existing_credentials.refresh_token:
|
|
964
|
+
fallback_refresh_token = existing_credentials.refresh_token
|
|
965
|
+
logger.info(
|
|
966
|
+
"OAuth callback response omitted refresh token; preserving existing refresh token from credential store."
|
|
967
|
+
)
|
|
968
|
+
except Exception as e:
|
|
969
|
+
logger.debug(
|
|
970
|
+
f"Could not check credential store for existing refresh token: {e}"
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
if fallback_refresh_token:
|
|
974
|
+
credentials = Credentials(
|
|
975
|
+
token=credentials.token,
|
|
976
|
+
refresh_token=fallback_refresh_token,
|
|
977
|
+
id_token=getattr(credentials, "id_token", None),
|
|
978
|
+
token_uri=credentials.token_uri,
|
|
979
|
+
client_id=credentials.client_id,
|
|
980
|
+
client_secret=credentials.client_secret,
|
|
981
|
+
scopes=credentials.scopes,
|
|
982
|
+
expiry=credentials.expiry,
|
|
983
|
+
quota_project_id=getattr(credentials, "quota_project_id", None),
|
|
984
|
+
)
|
|
985
|
+
else:
|
|
986
|
+
logger.warning(
|
|
987
|
+
"OAuth callback did not include a refresh token and no previous refresh token was available to preserve."
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
if not stateless_mode:
|
|
991
|
+
# Save the credentials before updating session state so both stores stay in sync.
|
|
992
|
+
stored = await asyncio.to_thread(
|
|
993
|
+
credential_store.store_credential, user_google_email, credentials
|
|
994
|
+
)
|
|
995
|
+
if not stored:
|
|
996
|
+
logger.warning(
|
|
997
|
+
"Credential store rejected updated credentials for %s; aborting session persistence.",
|
|
998
|
+
user_google_email,
|
|
999
|
+
)
|
|
1000
|
+
raise RuntimeError(
|
|
1001
|
+
f"Failed to persist credentials for {user_google_email}; "
|
|
1002
|
+
"session state was not updated."
|
|
1003
|
+
)
|
|
1004
|
+
|
|
1005
|
+
session_user = store.get_user_by_mcp_session(session_id) if session_id else None
|
|
1006
|
+
if session_user and session_user != user_google_email:
|
|
1007
|
+
logger.info(
|
|
1008
|
+
f"[handle_auth_callback] Session belongs to {session_user}; storing "
|
|
1009
|
+
f"{user_google_email} without a session binding"
|
|
1010
|
+
)
|
|
1011
|
+
session_id = None
|
|
1012
|
+
|
|
1013
|
+
# Always save to OAuth21SessionStore for centralized management
|
|
1014
|
+
store.store_session(
|
|
1015
|
+
user_email=user_google_email,
|
|
1016
|
+
access_token=credentials.token,
|
|
1017
|
+
refresh_token=credentials.refresh_token,
|
|
1018
|
+
token_uri=credentials.token_uri,
|
|
1019
|
+
client_id=credentials.client_id,
|
|
1020
|
+
client_secret=credentials.client_secret,
|
|
1021
|
+
scopes=credentials.scopes,
|
|
1022
|
+
expiry=credentials.expiry,
|
|
1023
|
+
mcp_session_id=session_id,
|
|
1024
|
+
issuer="https://accounts.google.com", # Add issuer for Google tokens
|
|
1025
|
+
)
|
|
1026
|
+
|
|
1027
|
+
# If session_id is provided, also save to session cache for compatibility
|
|
1028
|
+
if session_id:
|
|
1029
|
+
save_credentials_to_session(session_id, credentials)
|
|
1030
|
+
|
|
1031
|
+
return user_google_email, credentials
|
|
1032
|
+
|
|
1033
|
+
except Exception as e: # Catch specific exceptions like FlowExchangeError if needed
|
|
1034
|
+
logger.error(f"Error handling auth callback: {e}")
|
|
1035
|
+
raise # Re-raise for the caller
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
def get_credentials(
|
|
1039
|
+
user_google_email: Optional[str], # Can be None if relying on session_id
|
|
1040
|
+
required_scopes: List[str],
|
|
1041
|
+
client_secrets_path: Optional[str] = None,
|
|
1042
|
+
credentials_base_dir: str = DEFAULT_CREDENTIALS_DIR,
|
|
1043
|
+
session_id: Optional[str] = None,
|
|
1044
|
+
) -> Optional[Credentials]:
|
|
1045
|
+
"""
|
|
1046
|
+
Retrieves stored credentials, prioritizing OAuth 2.1 store, then session, then file. Refreshes if necessary.
|
|
1047
|
+
In single-user mode, bypasses session mapping. If user_google_email is provided, only credentials
|
|
1048
|
+
for that email are used and the function returns None instead of falling back to any available
|
|
1049
|
+
credentials. If user_google_email is not provided, any available credentials may be used.
|
|
1050
|
+
|
|
1051
|
+
Args:
|
|
1052
|
+
user_google_email: Optional user's Google email.
|
|
1053
|
+
required_scopes: List of scopes the credentials must have.
|
|
1054
|
+
client_secrets_path: Optional path to client secrets (legacy; refresh uses embedded client info).
|
|
1055
|
+
credentials_base_dir: Base directory for credential files.
|
|
1056
|
+
session_id: Optional MCP session ID.
|
|
1057
|
+
|
|
1058
|
+
Returns:
|
|
1059
|
+
Valid Credentials object or None.
|
|
1060
|
+
"""
|
|
1061
|
+
skip_session_cache = False
|
|
1062
|
+
# First, try OAuth 2.1 session store if we have a session_id (FastMCP session)
|
|
1063
|
+
if session_id:
|
|
1064
|
+
try:
|
|
1065
|
+
store = get_oauth21_session_store()
|
|
1066
|
+
|
|
1067
|
+
session_user = store.get_user_by_mcp_session(session_id)
|
|
1068
|
+
if user_google_email and session_user and session_user != user_google_email:
|
|
1069
|
+
logger.info(
|
|
1070
|
+
f"[get_credentials] Session user {session_user} doesn't match requested {user_google_email}; "
|
|
1071
|
+
"skipping session store"
|
|
1072
|
+
)
|
|
1073
|
+
skip_session_cache = True
|
|
1074
|
+
else:
|
|
1075
|
+
# Try to get credentials by MCP session
|
|
1076
|
+
credentials = store.get_credentials_by_mcp_session(session_id)
|
|
1077
|
+
if credentials:
|
|
1078
|
+
logger.info(
|
|
1079
|
+
f"[get_credentials] Found OAuth 2.1 credentials for MCP session {session_id}"
|
|
1080
|
+
)
|
|
1081
|
+
|
|
1082
|
+
# Refresh invalid credentials before checking scopes
|
|
1083
|
+
if (not credentials.valid) and credentials.refresh_token:
|
|
1084
|
+
try:
|
|
1085
|
+
credentials.refresh(Request())
|
|
1086
|
+
logger.info(
|
|
1087
|
+
f"[get_credentials] Refreshed OAuth 2.1 credentials for session {session_id}"
|
|
1088
|
+
)
|
|
1089
|
+
# Update stored credentials
|
|
1090
|
+
user_email = store.get_user_by_mcp_session(session_id)
|
|
1091
|
+
if user_email:
|
|
1092
|
+
# Persist to file so rotated refresh tokens survive restarts
|
|
1093
|
+
persist_succeeded = True
|
|
1094
|
+
if not is_stateless_mode():
|
|
1095
|
+
try:
|
|
1096
|
+
credential_store = get_credential_store()
|
|
1097
|
+
persist_succeeded = (
|
|
1098
|
+
credential_store.store_credential(
|
|
1099
|
+
user_email, credentials
|
|
1100
|
+
)
|
|
1101
|
+
)
|
|
1102
|
+
if not persist_succeeded:
|
|
1103
|
+
logger.warning(
|
|
1104
|
+
"[get_credentials] Credential store rejected refreshed OAuth 2.1 credentials for user %s; skipping session update.",
|
|
1105
|
+
user_email,
|
|
1106
|
+
)
|
|
1107
|
+
except Exception as persist_error:
|
|
1108
|
+
persist_succeeded = False
|
|
1109
|
+
logger.warning(
|
|
1110
|
+
f"[get_credentials] Failed to persist refreshed OAuth 2.1 credentials for user {user_email}: {persist_error}"
|
|
1111
|
+
)
|
|
1112
|
+
|
|
1113
|
+
if not persist_succeeded and not is_stateless_mode():
|
|
1114
|
+
logger.warning(
|
|
1115
|
+
"[get_credentials] Refreshed OAuth 2.1 credentials for user %s were not persisted; discarding in-memory refresh result.",
|
|
1116
|
+
user_email,
|
|
1117
|
+
)
|
|
1118
|
+
return None
|
|
1119
|
+
|
|
1120
|
+
if persist_succeeded or is_stateless_mode():
|
|
1121
|
+
store.store_session(
|
|
1122
|
+
user_email=user_email,
|
|
1123
|
+
access_token=credentials.token,
|
|
1124
|
+
refresh_token=credentials.refresh_token,
|
|
1125
|
+
token_uri=credentials.token_uri,
|
|
1126
|
+
client_id=credentials.client_id,
|
|
1127
|
+
client_secret=credentials.client_secret,
|
|
1128
|
+
scopes=credentials.scopes,
|
|
1129
|
+
expiry=credentials.expiry,
|
|
1130
|
+
mcp_session_id=session_id,
|
|
1131
|
+
issuer="https://accounts.google.com",
|
|
1132
|
+
)
|
|
1133
|
+
except Exception as e:
|
|
1134
|
+
logger.error(
|
|
1135
|
+
f"[get_credentials] Failed to refresh OAuth 2.1 credentials: {e}"
|
|
1136
|
+
)
|
|
1137
|
+
return None
|
|
1138
|
+
|
|
1139
|
+
# Check scopes after refresh so stale metadata doesn't block valid tokens
|
|
1140
|
+
if not has_required_scopes(credentials.scopes, required_scopes):
|
|
1141
|
+
logger.warning(
|
|
1142
|
+
f"[get_credentials] OAuth 2.1 credentials lack required scopes. Need: {required_scopes}, Have: {credentials.scopes}"
|
|
1143
|
+
)
|
|
1144
|
+
return None
|
|
1145
|
+
|
|
1146
|
+
if credentials.valid:
|
|
1147
|
+
return credentials
|
|
1148
|
+
|
|
1149
|
+
return None
|
|
1150
|
+
except ImportError:
|
|
1151
|
+
pass # OAuth 2.1 store not available
|
|
1152
|
+
except Exception as e:
|
|
1153
|
+
logger.debug(f"[get_credentials] Error checking OAuth 2.1 store: {e}")
|
|
1154
|
+
|
|
1155
|
+
# Check for single-user mode
|
|
1156
|
+
if os.getenv("MCP_SINGLE_USER_MODE") == "1":
|
|
1157
|
+
logger.info(
|
|
1158
|
+
"[get_credentials] Single-user mode: bypassing session mapping, finding any credentials"
|
|
1159
|
+
)
|
|
1160
|
+
# If a specific email was requested, try to load that user's credentials first
|
|
1161
|
+
# to avoid session binding conflicts when multiple credential files exist
|
|
1162
|
+
if user_google_email:
|
|
1163
|
+
credential_store = get_credential_store()
|
|
1164
|
+
user_google_email = _stored_user_email(credential_store, user_google_email)
|
|
1165
|
+
credentials = credential_store.get_credential(user_google_email)
|
|
1166
|
+
if credentials:
|
|
1167
|
+
logger.info(
|
|
1168
|
+
f"[get_credentials] Single-user mode: found credentials for requested user {user_google_email}"
|
|
1169
|
+
)
|
|
1170
|
+
found_user_email = user_google_email
|
|
1171
|
+
else:
|
|
1172
|
+
logger.info(
|
|
1173
|
+
"[get_credentials] Single-user mode: no credentials for requested "
|
|
1174
|
+
f"user {user_google_email}; not falling back to another user"
|
|
1175
|
+
)
|
|
1176
|
+
return None
|
|
1177
|
+
else:
|
|
1178
|
+
credentials, found_user_email = _find_any_credentials(credentials_base_dir)
|
|
1179
|
+
if not credentials:
|
|
1180
|
+
logger.info(
|
|
1181
|
+
f"[get_credentials] Single-user mode: No credentials found in {credentials_base_dir}"
|
|
1182
|
+
)
|
|
1183
|
+
return None
|
|
1184
|
+
|
|
1185
|
+
# Use the email from the credential file if not provided
|
|
1186
|
+
# This ensures we can save refreshed credentials even when the token is expired
|
|
1187
|
+
if not user_google_email and found_user_email:
|
|
1188
|
+
user_google_email = found_user_email
|
|
1189
|
+
logger.debug(
|
|
1190
|
+
f"[get_credentials] Single-user mode: using email {user_google_email} from credential file"
|
|
1191
|
+
)
|
|
1192
|
+
else:
|
|
1193
|
+
credentials: Optional[Credentials] = None
|
|
1194
|
+
|
|
1195
|
+
# Session ID should be provided by the caller
|
|
1196
|
+
if not session_id:
|
|
1197
|
+
logger.debug("[get_credentials] No session_id provided")
|
|
1198
|
+
|
|
1199
|
+
logger.debug(
|
|
1200
|
+
f"[get_credentials] Called for user_google_email: '{user_google_email}', session_id: '{session_id}', required_scopes: {required_scopes}"
|
|
1201
|
+
)
|
|
1202
|
+
|
|
1203
|
+
if session_id and not skip_session_cache:
|
|
1204
|
+
credentials = load_credentials_from_session(session_id)
|
|
1205
|
+
if credentials:
|
|
1206
|
+
logger.debug(
|
|
1207
|
+
f"[get_credentials] Loaded credentials from session for session_id '{session_id}'."
|
|
1208
|
+
)
|
|
1209
|
+
|
|
1210
|
+
if not credentials and user_google_email:
|
|
1211
|
+
if not is_stateless_mode():
|
|
1212
|
+
logger.debug(
|
|
1213
|
+
f"[get_credentials] No session credentials, trying credential store for user_google_email '{user_google_email}'."
|
|
1214
|
+
)
|
|
1215
|
+
store = get_credential_store()
|
|
1216
|
+
credentials = store.get_credential(user_google_email)
|
|
1217
|
+
else:
|
|
1218
|
+
logger.debug(
|
|
1219
|
+
f"[get_credentials] No session credentials, skipping file store in stateless mode for user_google_email '{user_google_email}'."
|
|
1220
|
+
)
|
|
1221
|
+
|
|
1222
|
+
if not credentials:
|
|
1223
|
+
logger.info(
|
|
1224
|
+
f"[get_credentials] No credentials found for user '{user_google_email}' or session '{session_id}'."
|
|
1225
|
+
)
|
|
1226
|
+
return None
|
|
1227
|
+
|
|
1228
|
+
logger.debug(
|
|
1229
|
+
f"[get_credentials] Credentials found. Scopes: {credentials.scopes}, Valid: {credentials.valid}, Expired: {credentials.expired}"
|
|
1230
|
+
)
|
|
1231
|
+
|
|
1232
|
+
# Attempt refresh before checking scopes — the scope check validates against
|
|
1233
|
+
# credentials.scopes which is set at authorization time and not updated by the
|
|
1234
|
+
# google-auth library on refresh. Checking scopes first would block a valid
|
|
1235
|
+
# refresh attempt when stored scope metadata is stale.
|
|
1236
|
+
if credentials.valid:
|
|
1237
|
+
logger.debug(
|
|
1238
|
+
f"[get_credentials] Credentials are valid. User: '{user_google_email}', Session: '{session_id}'"
|
|
1239
|
+
)
|
|
1240
|
+
elif credentials.refresh_token:
|
|
1241
|
+
logger.info(
|
|
1242
|
+
f"[get_credentials] Credentials not valid. Attempting refresh. User: '{user_google_email}', Session: '{session_id}'"
|
|
1243
|
+
)
|
|
1244
|
+
try:
|
|
1245
|
+
logger.debug(
|
|
1246
|
+
"[get_credentials] Refreshing token using embedded client credentials"
|
|
1247
|
+
)
|
|
1248
|
+
credentials.refresh(Request())
|
|
1249
|
+
refreshed_email = _id_token_email(credentials)
|
|
1250
|
+
if (
|
|
1251
|
+
user_google_email
|
|
1252
|
+
and refreshed_email
|
|
1253
|
+
and normalize_principal_email(refreshed_email)
|
|
1254
|
+
!= normalize_principal_email(user_google_email)
|
|
1255
|
+
):
|
|
1256
|
+
logger.error(
|
|
1257
|
+
"[get_credentials] Refreshed credentials belong to %s, not %s; discarding them",
|
|
1258
|
+
refreshed_email,
|
|
1259
|
+
user_google_email,
|
|
1260
|
+
)
|
|
1261
|
+
return None
|
|
1262
|
+
logger.info(
|
|
1263
|
+
f"[get_credentials] Credentials refreshed successfully. User: '{user_google_email}', Session: '{session_id}'"
|
|
1264
|
+
)
|
|
1265
|
+
|
|
1266
|
+
# Save refreshed credentials (skip file save in stateless mode)
|
|
1267
|
+
persist_succeeded = True
|
|
1268
|
+
if user_google_email: # Always save to credential store if email is known
|
|
1269
|
+
if not is_stateless_mode():
|
|
1270
|
+
try:
|
|
1271
|
+
credential_store = get_credential_store()
|
|
1272
|
+
persist_succeeded = credential_store.store_credential(
|
|
1273
|
+
user_google_email, credentials
|
|
1274
|
+
)
|
|
1275
|
+
except Exception as persist_error:
|
|
1276
|
+
persist_succeeded = False
|
|
1277
|
+
logger.warning(
|
|
1278
|
+
"[get_credentials] Failed to persist refreshed credentials for user %s: %s",
|
|
1279
|
+
user_google_email,
|
|
1280
|
+
persist_error,
|
|
1281
|
+
)
|
|
1282
|
+
|
|
1283
|
+
if not persist_succeeded:
|
|
1284
|
+
logger.warning(
|
|
1285
|
+
"[get_credentials] Credential store rejected refreshed credentials for user %s; skipping session update.",
|
|
1286
|
+
user_google_email,
|
|
1287
|
+
)
|
|
1288
|
+
else:
|
|
1289
|
+
logger.info(
|
|
1290
|
+
f"Skipping credential file save in stateless mode for {user_google_email}"
|
|
1291
|
+
)
|
|
1292
|
+
|
|
1293
|
+
if not persist_succeeded and not is_stateless_mode():
|
|
1294
|
+
logger.warning(
|
|
1295
|
+
"[get_credentials] Refreshed credentials for user %s were not persisted; discarding in-memory refresh result.",
|
|
1296
|
+
user_google_email,
|
|
1297
|
+
)
|
|
1298
|
+
return None
|
|
1299
|
+
|
|
1300
|
+
if persist_succeeded or is_stateless_mode():
|
|
1301
|
+
# Also update OAuth21SessionStore
|
|
1302
|
+
store = get_oauth21_session_store()
|
|
1303
|
+
mcp_session_id = session_id
|
|
1304
|
+
if skip_session_cache:
|
|
1305
|
+
existing_session = store.get_session_info(user_google_email)
|
|
1306
|
+
mcp_session_id = (existing_session or {}).get("mcp_session_id")
|
|
1307
|
+
store.store_session(
|
|
1308
|
+
user_email=user_google_email,
|
|
1309
|
+
access_token=credentials.token,
|
|
1310
|
+
refresh_token=credentials.refresh_token,
|
|
1311
|
+
token_uri=credentials.token_uri,
|
|
1312
|
+
client_id=credentials.client_id,
|
|
1313
|
+
client_secret=credentials.client_secret,
|
|
1314
|
+
scopes=credentials.scopes,
|
|
1315
|
+
expiry=credentials.expiry,
|
|
1316
|
+
mcp_session_id=mcp_session_id,
|
|
1317
|
+
issuer="https://accounts.google.com", # Add issuer for Google tokens
|
|
1318
|
+
)
|
|
1319
|
+
|
|
1320
|
+
if (
|
|
1321
|
+
session_id
|
|
1322
|
+
and not skip_session_cache
|
|
1323
|
+
and (persist_succeeded or is_stateless_mode())
|
|
1324
|
+
):
|
|
1325
|
+
# Update session cache if it was the source or is active
|
|
1326
|
+
save_credentials_to_session(session_id, credentials)
|
|
1327
|
+
except RefreshError as e:
|
|
1328
|
+
logger.warning(
|
|
1329
|
+
f"[get_credentials] RefreshError - token expired/revoked: {e}. User: '{user_google_email}', Session: '{session_id}'"
|
|
1330
|
+
)
|
|
1331
|
+
# For RefreshError, we should return None to trigger reauthentication
|
|
1332
|
+
return None
|
|
1333
|
+
except Exception as e:
|
|
1334
|
+
logger.error(
|
|
1335
|
+
f"[get_credentials] Error refreshing credentials: {e}. User: '{user_google_email}', Session: '{session_id}'",
|
|
1336
|
+
exc_info=True,
|
|
1337
|
+
)
|
|
1338
|
+
return None # Failed to refresh
|
|
1339
|
+
else:
|
|
1340
|
+
logger.warning(
|
|
1341
|
+
f"[get_credentials] Credentials invalid/cannot refresh. Valid: {credentials.valid}, Refresh Token: {credentials.refresh_token is not None}. User: '{user_google_email}', Session: '{session_id}'"
|
|
1342
|
+
)
|
|
1343
|
+
return None
|
|
1344
|
+
|
|
1345
|
+
# Check scopes after refresh so stale scope metadata doesn't block valid tokens.
|
|
1346
|
+
# Uses hierarchy-aware check (e.g. gmail.modify satisfies gmail.readonly).
|
|
1347
|
+
if not has_required_scopes(credentials.scopes, required_scopes):
|
|
1348
|
+
logger.warning(
|
|
1349
|
+
f"[get_credentials] Credentials lack required scopes. Need: {required_scopes}, Have: {credentials.scopes}. User: '{user_google_email}', Session: '{session_id}'"
|
|
1350
|
+
)
|
|
1351
|
+
return None # Re-authentication needed for scopes
|
|
1352
|
+
|
|
1353
|
+
logger.debug(
|
|
1354
|
+
f"[get_credentials] Credentials have sufficient scopes. User: '{user_google_email}', Session: '{session_id}'"
|
|
1355
|
+
)
|
|
1356
|
+
return credentials
|
|
1357
|
+
|
|
1358
|
+
|
|
1359
|
+
def get_user_info(
|
|
1360
|
+
credentials: Credentials, *, skip_valid_check: bool = False
|
|
1361
|
+
) -> Optional[Dict[str, Any]]:
|
|
1362
|
+
"""Fetches basic user profile information (requires userinfo.email scope)."""
|
|
1363
|
+
if not credentials:
|
|
1364
|
+
logger.error("Cannot get user info: Missing credentials.")
|
|
1365
|
+
return None
|
|
1366
|
+
if not skip_valid_check and not credentials.valid:
|
|
1367
|
+
logger.error("Cannot get user info: Invalid credentials.")
|
|
1368
|
+
return None
|
|
1369
|
+
service = None
|
|
1370
|
+
try:
|
|
1371
|
+
# Using googleapiclient discovery to get user info
|
|
1372
|
+
# Requires 'google-api-python-client' library
|
|
1373
|
+
authorized_http = google_auth_httplib2.AuthorizedHttp(
|
|
1374
|
+
credentials, http=httplib2.Http(timeout=_USER_INFO_TIMEOUT_SECONDS)
|
|
1375
|
+
)
|
|
1376
|
+
service = build("oauth2", "v2", http=authorized_http)
|
|
1377
|
+
user_info = service.userinfo().get().execute()
|
|
1378
|
+
logger.info(f"Successfully fetched user info: {user_info.get('email')}")
|
|
1379
|
+
return user_info
|
|
1380
|
+
except HttpError as e:
|
|
1381
|
+
logger.error(f"HttpError fetching user info: {e.status_code} {e.reason}")
|
|
1382
|
+
# Handle specific errors, e.g., 401 Unauthorized might mean token issue
|
|
1383
|
+
return None
|
|
1384
|
+
except Exception as e:
|
|
1385
|
+
logger.error(f"Unexpected error fetching user info: {e}")
|
|
1386
|
+
return None
|
|
1387
|
+
finally:
|
|
1388
|
+
if service:
|
|
1389
|
+
service.close()
|
|
1390
|
+
|
|
1391
|
+
|
|
1392
|
+
# --- Centralized Google Service Authentication ---
|
|
1393
|
+
|
|
1394
|
+
|
|
1395
|
+
class GoogleAuthenticationError(Exception):
|
|
1396
|
+
"""Exception raised when Google authentication is required or fails."""
|
|
1397
|
+
|
|
1398
|
+
def __init__(self, message: str, auth_url: Optional[str] = None):
|
|
1399
|
+
super().__init__(message)
|
|
1400
|
+
self.auth_url = auth_url
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
async def get_authenticated_google_service(
|
|
1404
|
+
service_name: str, # "gmail", "calendar", "drive", "docs"
|
|
1405
|
+
version: str, # "v1", "v3"
|
|
1406
|
+
tool_name: str, # For logging/debugging
|
|
1407
|
+
user_google_email: str, # Required - no more Optional
|
|
1408
|
+
required_scopes: List[str],
|
|
1409
|
+
session_id: Optional[str] = None, # Session context for logging
|
|
1410
|
+
) -> tuple[Any, str]:
|
|
1411
|
+
"""
|
|
1412
|
+
Centralized Google service authentication for all MCP tools.
|
|
1413
|
+
Returns (service, user_email) on success or raises GoogleAuthenticationError.
|
|
1414
|
+
|
|
1415
|
+
Args:
|
|
1416
|
+
service_name: The Google service name ("gmail", "calendar", "drive", "docs")
|
|
1417
|
+
version: The API version ("v1", "v3", etc.)
|
|
1418
|
+
tool_name: The name of the calling tool (for logging/debugging)
|
|
1419
|
+
user_google_email: The user's Google email address (required)
|
|
1420
|
+
required_scopes: List of required OAuth scopes
|
|
1421
|
+
|
|
1422
|
+
Returns:
|
|
1423
|
+
tuple[service, user_email] on success
|
|
1424
|
+
|
|
1425
|
+
Raises:
|
|
1426
|
+
GoogleAuthenticationError: When authentication is required or fails
|
|
1427
|
+
"""
|
|
1428
|
+
|
|
1429
|
+
# Try to get FastMCP session ID if not provided
|
|
1430
|
+
if not session_id:
|
|
1431
|
+
try:
|
|
1432
|
+
# First try context variable (works in async context)
|
|
1433
|
+
session_id = get_fastmcp_session_id()
|
|
1434
|
+
if session_id:
|
|
1435
|
+
logger.debug(
|
|
1436
|
+
f"[{tool_name}] Got FastMCP session ID from context: {session_id}"
|
|
1437
|
+
)
|
|
1438
|
+
else:
|
|
1439
|
+
logger.debug(
|
|
1440
|
+
f"[{tool_name}] Context variable returned None/empty session ID"
|
|
1441
|
+
)
|
|
1442
|
+
except Exception as e:
|
|
1443
|
+
logger.debug(
|
|
1444
|
+
f"[{tool_name}] Could not get FastMCP session from context: {e}"
|
|
1445
|
+
)
|
|
1446
|
+
|
|
1447
|
+
# Fallback to direct FastMCP context if context variable not set
|
|
1448
|
+
if not session_id and get_fastmcp_context:
|
|
1449
|
+
try:
|
|
1450
|
+
fastmcp_ctx = get_fastmcp_context()
|
|
1451
|
+
if fastmcp_ctx and hasattr(fastmcp_ctx, "session_id"):
|
|
1452
|
+
session_id = fastmcp_ctx.session_id
|
|
1453
|
+
logger.debug(
|
|
1454
|
+
f"[{tool_name}] Got FastMCP session ID directly: {session_id}"
|
|
1455
|
+
)
|
|
1456
|
+
else:
|
|
1457
|
+
logger.debug(
|
|
1458
|
+
f"[{tool_name}] FastMCP context exists but no session_id attribute"
|
|
1459
|
+
)
|
|
1460
|
+
except Exception as e:
|
|
1461
|
+
logger.debug(
|
|
1462
|
+
f"[{tool_name}] Could not get FastMCP context directly: {e}"
|
|
1463
|
+
)
|
|
1464
|
+
|
|
1465
|
+
# Final fallback: log if we still don't have session_id
|
|
1466
|
+
if not session_id:
|
|
1467
|
+
logger.warning(
|
|
1468
|
+
f"[{tool_name}] Unable to obtain FastMCP session ID from any source"
|
|
1469
|
+
)
|
|
1470
|
+
|
|
1471
|
+
logger.info(
|
|
1472
|
+
f"[{tool_name}] Attempting to get authenticated {service_name} service. Email: '{user_google_email}', Session: '{session_id}'"
|
|
1473
|
+
)
|
|
1474
|
+
|
|
1475
|
+
# Validate email format
|
|
1476
|
+
if not user_google_email or "@" not in user_google_email:
|
|
1477
|
+
error_msg = f"Authentication required for {tool_name}. No valid 'user_google_email' provided. Please provide a valid Google email address."
|
|
1478
|
+
logger.info(f"[{tool_name}] {error_msg}")
|
|
1479
|
+
raise GoogleAuthenticationError(error_msg)
|
|
1480
|
+
|
|
1481
|
+
credentials = await asyncio.to_thread(
|
|
1482
|
+
get_credentials,
|
|
1483
|
+
user_google_email=user_google_email,
|
|
1484
|
+
required_scopes=required_scopes,
|
|
1485
|
+
client_secrets_path=CONFIG_CLIENT_SECRETS_PATH,
|
|
1486
|
+
session_id=session_id, # Pass through session context
|
|
1487
|
+
)
|
|
1488
|
+
|
|
1489
|
+
if not credentials or not credentials.valid:
|
|
1490
|
+
logger.warning(
|
|
1491
|
+
f"[{tool_name}] No valid credentials. Email: '{user_google_email}'."
|
|
1492
|
+
)
|
|
1493
|
+
logger.info(
|
|
1494
|
+
f"[{tool_name}] Valid email '{user_google_email}' provided, initiating auth flow."
|
|
1495
|
+
)
|
|
1496
|
+
|
|
1497
|
+
redirect_uri = get_oauth_redirect_uri()
|
|
1498
|
+
# Only stdio legacy OAuth depends on the standalone callback server; the
|
|
1499
|
+
# helper no-ops in other transports and binds the port lazily (#832).
|
|
1500
|
+
from auth.oauth_callback_server import ensure_stdio_oauth_callback_available
|
|
1501
|
+
|
|
1502
|
+
success, error_msg = await asyncio.to_thread(
|
|
1503
|
+
ensure_stdio_oauth_callback_available
|
|
1504
|
+
)
|
|
1505
|
+
if not success:
|
|
1506
|
+
error_detail = f" ({error_msg})" if error_msg else ""
|
|
1507
|
+
raise GoogleAuthenticationError(
|
|
1508
|
+
f"Cannot initiate OAuth flow - callback server unavailable{error_detail}"
|
|
1509
|
+
)
|
|
1510
|
+
|
|
1511
|
+
# Generate auth URL and raise exception with it
|
|
1512
|
+
auth_response = await start_auth_flow(
|
|
1513
|
+
user_google_email=user_google_email,
|
|
1514
|
+
service_name=f"Google {service_name.title()}",
|
|
1515
|
+
redirect_uri=redirect_uri,
|
|
1516
|
+
principal_source=(
|
|
1517
|
+
"gateway_assertion" if is_trust_gateway_identity() else None
|
|
1518
|
+
),
|
|
1519
|
+
)
|
|
1520
|
+
|
|
1521
|
+
# Extract the auth URL from the response and raise with it
|
|
1522
|
+
raise GoogleAuthenticationError(auth_response)
|
|
1523
|
+
|
|
1524
|
+
try:
|
|
1525
|
+
service = build_google_service(service_name, version, credentials)
|
|
1526
|
+
log_user_email = user_google_email
|
|
1527
|
+
|
|
1528
|
+
# Try to get email from credentials if needed for validation
|
|
1529
|
+
if credentials and credentials.id_token:
|
|
1530
|
+
try:
|
|
1531
|
+
# Decode without verification (just to get email for logging)
|
|
1532
|
+
decoded_token = jwt.decode(
|
|
1533
|
+
credentials.id_token, options={"verify_signature": False}
|
|
1534
|
+
)
|
|
1535
|
+
token_email = decoded_token.get("email")
|
|
1536
|
+
if token_email:
|
|
1537
|
+
log_user_email = token_email
|
|
1538
|
+
logger.info(f"[{tool_name}] Token email: {token_email}")
|
|
1539
|
+
except Exception as e:
|
|
1540
|
+
logger.debug(f"[{tool_name}] Could not decode id_token: {e}")
|
|
1541
|
+
|
|
1542
|
+
logger.info(
|
|
1543
|
+
f"[{tool_name}] Successfully authenticated {service_name} service for user: {log_user_email}"
|
|
1544
|
+
)
|
|
1545
|
+
return service, log_user_email
|
|
1546
|
+
|
|
1547
|
+
except Exception as e:
|
|
1548
|
+
error_msg = f"[{tool_name}] Failed to build {service_name} service: {str(e)}"
|
|
1549
|
+
logger.error(error_msg, exc_info=True)
|
|
1550
|
+
raise GoogleAuthenticationError(error_msg)
|