@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.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +34 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,1332 @@
1
+ """
2
+ OAuth 2.1 Session Store for Google Services
3
+
4
+ This module provides a global store for OAuth 2.1 authenticated sessions
5
+ that can be accessed by Google service decorators. It also includes
6
+ session context management and credential conversion functionality.
7
+ """
8
+
9
+ import contextvars
10
+ import json
11
+ import logging
12
+ import os
13
+ from typing import Dict, Optional, Any, Tuple, Callable, IO
14
+ from threading import RLock
15
+ from datetime import datetime, timedelta, timezone
16
+ from dataclasses import dataclass
17
+
18
+ try:
19
+ import fcntl
20
+ except ImportError: # pragma: no cover - Windows
21
+ fcntl = None
22
+
23
+ from fastmcp.server.auth import AccessToken
24
+ from fastmcp.server.dependencies import get_http_headers
25
+ from google.oauth2.credentials import Credentials
26
+ from auth.oauth_config import is_external_oauth21_provider
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ def _lock_file_exclusive(file_handle: IO[str]) -> None:
32
+ """Acquire an exclusive lock when supported by the platform."""
33
+ if fcntl is None:
34
+ return
35
+ fcntl.flock(file_handle.fileno(), fcntl.LOCK_EX)
36
+
37
+
38
+ def _unlock_file(file_handle: IO[str]) -> None:
39
+ """Release a file lock when supported by the platform."""
40
+ if fcntl is None:
41
+ return
42
+ fcntl.flock(file_handle.fileno(), fcntl.LOCK_UN)
43
+
44
+
45
+ def _get_default_oauth_state_file() -> str:
46
+ """Resolve the shared OAuth state file path inside the credentials directory."""
47
+ workspace_creds_dir = os.getenv("WORKSPACE_MCP_CREDENTIALS_DIR")
48
+ if workspace_creds_dir:
49
+ base_dir = os.path.expanduser(workspace_creds_dir)
50
+ else:
51
+ google_creds_dir = os.getenv("GOOGLE_MCP_CREDENTIALS_DIR")
52
+ if google_creds_dir:
53
+ base_dir = os.path.expanduser(google_creds_dir)
54
+ else:
55
+ home_dir = os.path.expanduser("~")
56
+ if home_dir and home_dir != "~":
57
+ base_dir = os.path.join(
58
+ home_dir, ".google_workspace_mcp", "credentials"
59
+ )
60
+ else:
61
+ base_dir = os.path.join(os.getcwd(), ".credentials")
62
+
63
+ return os.path.join(base_dir, "oauth_states.json")
64
+
65
+
66
+ def _normalize_expiry_to_naive_utc(expiry: Optional[Any]) -> Optional[datetime]:
67
+ """
68
+ Convert expiry values to timezone-naive UTC datetimes for google-auth compatibility.
69
+
70
+ Naive datetime inputs are assumed to already represent UTC and are returned unchanged so that
71
+ google-auth Credentials receive naive UTC datetimes for expiry comparison.
72
+ """
73
+ if expiry is None:
74
+ return None
75
+
76
+ if isinstance(expiry, datetime):
77
+ if expiry.tzinfo is not None:
78
+ try:
79
+ return expiry.astimezone(timezone.utc).replace(tzinfo=None)
80
+ except Exception: # pragma: no cover - defensive
81
+ logger.debug(
82
+ "Failed to normalize aware expiry; returning without tzinfo"
83
+ )
84
+ return expiry.replace(tzinfo=None)
85
+ return expiry # Already naive; assumed to represent UTC
86
+
87
+ if isinstance(expiry, str):
88
+ try:
89
+ parsed = datetime.fromisoformat(expiry.replace("Z", "+00:00"))
90
+ except ValueError:
91
+ logger.debug("Failed to parse expiry string '%s'", expiry)
92
+ return None
93
+ return _normalize_expiry_to_naive_utc(parsed)
94
+
95
+ logger.debug("Unsupported expiry type '%s' (%s)", expiry, type(expiry))
96
+ return None
97
+
98
+
99
+ # Context variable to store the current session information
100
+ _current_session_context: contextvars.ContextVar[Optional["SessionContext"]] = (
101
+ contextvars.ContextVar("current_session_context", default=None)
102
+ )
103
+
104
+
105
+ @dataclass
106
+ class SessionContext:
107
+ """Container for session-related information."""
108
+
109
+ session_id: Optional[str] = None
110
+ user_id: Optional[str] = None
111
+ auth_context: Optional[Any] = None
112
+ request: Optional[Any] = None
113
+ metadata: Dict[str, Any] = None
114
+ issuer: Optional[str] = None
115
+
116
+ def __post_init__(self):
117
+ if self.metadata is None:
118
+ self.metadata = {}
119
+
120
+
121
+ def set_session_context(context: Optional[SessionContext]):
122
+ """
123
+ Set the current session context.
124
+
125
+ Args:
126
+ context: The session context to set
127
+ """
128
+ _current_session_context.set(context)
129
+ if context:
130
+ logger.debug(
131
+ f"Set session context: session_id={context.session_id}, user_id={context.user_id}"
132
+ )
133
+ else:
134
+ logger.debug("Cleared session context")
135
+
136
+
137
+ def get_session_context() -> Optional[SessionContext]:
138
+ """
139
+ Get the current session context.
140
+
141
+ Returns:
142
+ The current session context or None
143
+ """
144
+ return _current_session_context.get()
145
+
146
+
147
+ def clear_session_context():
148
+ """Clear the current session context."""
149
+ set_session_context(None)
150
+
151
+
152
+ class SessionContextManager:
153
+ """
154
+ Context manager for temporarily setting session context.
155
+
156
+ Usage:
157
+ with SessionContextManager(session_context):
158
+ # Code that needs access to session context
159
+ pass
160
+ """
161
+
162
+ def __init__(self, context: Optional[SessionContext]):
163
+ self.context = context
164
+ self.token = None
165
+
166
+ def __enter__(self):
167
+ """Set the session context."""
168
+ self.token = _current_session_context.set(self.context)
169
+ return self.context
170
+
171
+ def __exit__(self, exc_type, exc_val, exc_tb):
172
+ """Reset the session context."""
173
+ if self.token:
174
+ _current_session_context.reset(self.token)
175
+
176
+
177
+ def extract_session_from_headers(headers: Dict[str, str]) -> Optional[str]:
178
+ """
179
+ Extract session ID from request headers.
180
+
181
+ Args:
182
+ headers: Request headers
183
+
184
+ Returns:
185
+ Session ID if found
186
+ """
187
+ # Try different header names
188
+ session_id = headers.get("mcp-session-id") or headers.get("Mcp-Session-Id")
189
+ if session_id:
190
+ return session_id
191
+
192
+ session_id = headers.get("x-session-id") or headers.get("X-Session-ID")
193
+ if session_id:
194
+ return session_id
195
+
196
+ # Try Authorization header for Bearer token
197
+ auth_header = headers.get("authorization") or headers.get("Authorization")
198
+ if auth_header and auth_header.lower().startswith("bearer "):
199
+ token = auth_header[7:] # Remove "Bearer " prefix
200
+ # Intentionally ignore empty tokens - "Bearer " with no token should not
201
+ # create a session context (avoids hash collisions on empty string)
202
+ if token:
203
+ # Use thread-safe lookup to find session by access token
204
+ store = get_oauth21_session_store()
205
+ session_id = store.find_session_id_for_access_token(token)
206
+ if session_id:
207
+ return session_id
208
+
209
+ # If no session found, create a temporary session ID from token hash
210
+ # This allows header-based authentication to work with session context
211
+ import hashlib
212
+
213
+ token_hash = hashlib.sha256(token.encode()).hexdigest()[:8]
214
+ return f"bearer_token_{token_hash}"
215
+
216
+ return None
217
+
218
+
219
+ # =============================================================================
220
+ # OAuth21SessionStore - Main Session Management
221
+ # =============================================================================
222
+
223
+
224
+ class OAuth21SessionStore:
225
+ """
226
+ Global store for OAuth 2.1 authenticated sessions.
227
+
228
+ This store maintains a mapping of user emails to their OAuth 2.1
229
+ authenticated credentials, allowing Google services to access them.
230
+ It also maintains a mapping from FastMCP session IDs to user emails.
231
+
232
+ Security: Sessions are bound to specific users and can only access
233
+ their own credentials.
234
+ """
235
+
236
+ def __init__(self, oauth_state_file: Optional[str] = None):
237
+ self._sessions: Dict[str, Dict[str, Any]] = {}
238
+ self._mcp_session_mapping: Dict[
239
+ str, str
240
+ ] = {} # Maps FastMCP session ID -> user email
241
+ self._session_auth_binding: Dict[
242
+ str, str
243
+ ] = {} # Maps session ID -> authenticated user email (immutable)
244
+ self._oauth_states: Dict[str, Dict[str, Any]] = {}
245
+ self._oauth_state_file = oauth_state_file or _get_default_oauth_state_file()
246
+ self._lock = RLock()
247
+
248
+ def _ensure_oauth_state_directory(self) -> None:
249
+ state_dir = os.path.dirname(self._oauth_state_file)
250
+ if state_dir:
251
+ os.makedirs(state_dir, mode=0o700, exist_ok=True)
252
+ try:
253
+ os.chmod(state_dir, 0o700)
254
+ except OSError:
255
+ logger.debug("Failed to update OAuth state directory permissions")
256
+ if os.path.exists(self._oauth_state_file):
257
+ try:
258
+ os.chmod(self._oauth_state_file, 0o600)
259
+ except OSError:
260
+ logger.debug("Failed to update OAuth state file permissions")
261
+
262
+ def _serialize_oauth_state_entry(
263
+ self, state_info: Dict[str, Any]
264
+ ) -> Dict[str, Any]:
265
+ serialized = {
266
+ "session_id": state_info.get("session_id"),
267
+ "code_verifier": state_info.get("code_verifier"),
268
+ "expected_user_email": state_info.get("expected_user_email"),
269
+ "principal_source": state_info.get("principal_source"),
270
+ # Retained for compatibility with state files written by the initial
271
+ # trusted-gateway implementation.
272
+ "user_email": state_info.get("user_email"),
273
+ "created_at": (
274
+ state_info["created_at"].astimezone(timezone.utc).isoformat()
275
+ if state_info.get("created_at")
276
+ else None
277
+ ),
278
+ "expires_at": (
279
+ state_info["expires_at"].astimezone(timezone.utc).isoformat()
280
+ if state_info.get("expires_at")
281
+ else None
282
+ ),
283
+ }
284
+ # Preserve the absence of this marker on old state entries. Gateway callbacks
285
+ # intentionally reject such entries during an upgrade rather than silently
286
+ # converting them into explicitly unbound legacy flows.
287
+ if "enforce_user_email_match" in state_info:
288
+ serialized["enforce_user_email_match"] = bool(
289
+ state_info["enforce_user_email_match"]
290
+ )
291
+ return serialized
292
+
293
+ def _deserialize_oauth_state_entry(
294
+ self, state_info: Dict[str, Any]
295
+ ) -> Dict[str, Any]:
296
+ deserialized = dict(state_info)
297
+ for field_name in ("created_at", "expires_at"):
298
+ raw_value = deserialized.get(field_name)
299
+ if isinstance(raw_value, str):
300
+ try:
301
+ parsed = datetime.fromisoformat(raw_value.replace("Z", "+00:00"))
302
+ except (TypeError, ValueError):
303
+ deserialized[field_name] = None
304
+ continue
305
+ if parsed.tzinfo is None:
306
+ parsed = parsed.replace(tzinfo=timezone.utc)
307
+ deserialized[field_name] = parsed
308
+ return deserialized
309
+
310
+ def _remove_expired_oauth_states_from_dict(
311
+ self, oauth_states: Dict[str, Dict[str, Any]]
312
+ ) -> bool:
313
+ now = datetime.now(timezone.utc)
314
+ expired_states = [
315
+ state
316
+ for state, data in oauth_states.items()
317
+ if data.get("expires_at") and data["expires_at"] <= now
318
+ ]
319
+ for state in expired_states:
320
+ del oauth_states[state]
321
+ return bool(expired_states)
322
+
323
+ def _load_oauth_states_from_file_handle(
324
+ self, file_handle: IO[str]
325
+ ) -> Tuple[Dict[str, Dict[str, Any]], bool]:
326
+ file_handle.seek(0)
327
+ raw = file_handle.read()
328
+ if not raw.strip():
329
+ return {}, False
330
+
331
+ try:
332
+ payload = json.loads(raw)
333
+ except json.JSONDecodeError:
334
+ logger.warning(
335
+ "OAuth state file %s is invalid JSON; resetting it",
336
+ self._oauth_state_file,
337
+ )
338
+ return {}, True
339
+
340
+ if not isinstance(payload, dict):
341
+ logger.warning(
342
+ "OAuth state file %s has unexpected contents; resetting it",
343
+ self._oauth_state_file,
344
+ )
345
+ return {}, True
346
+
347
+ oauth_states = {}
348
+ for state, state_info in payload.items():
349
+ if isinstance(state_info, dict):
350
+ oauth_states[state] = self._deserialize_oauth_state_entry(state_info)
351
+ removed_expired = self._remove_expired_oauth_states_from_dict(oauth_states)
352
+ return oauth_states, removed_expired
353
+
354
+ def _write_oauth_states_to_file_handle(
355
+ self,
356
+ file_handle: IO[str],
357
+ oauth_states: Dict[str, Dict[str, Any]],
358
+ ) -> None:
359
+ serialized = {
360
+ state: self._serialize_oauth_state_entry(state_info)
361
+ for state, state_info in oauth_states.items()
362
+ }
363
+ file_handle.seek(0)
364
+ file_handle.truncate()
365
+ json.dump(serialized, file_handle, indent=2, sort_keys=True)
366
+ file_handle.flush()
367
+ os.fsync(file_handle.fileno())
368
+ try:
369
+ os.chmod(self._oauth_state_file, 0o600)
370
+ except OSError:
371
+ logger.debug("Failed to update OAuth state file permissions")
372
+
373
+ def _update_shared_oauth_states(
374
+ self,
375
+ mutator: Callable[[Dict[str, Dict[str, Any]]], Tuple[Any, bool]],
376
+ ) -> Tuple[Any, Dict[str, Dict[str, Any]]]:
377
+ self._ensure_oauth_state_directory()
378
+ fd = os.open(self._oauth_state_file, os.O_RDWR | os.O_CREAT, 0o600)
379
+ with os.fdopen(fd, "r+", encoding="utf-8") as file_handle:
380
+ try:
381
+ os.chmod(self._oauth_state_file, 0o600)
382
+ except OSError:
383
+ logger.debug("Failed to update OAuth state file permissions")
384
+ _lock_file_exclusive(file_handle)
385
+ try:
386
+ oauth_states, cleaned_expired = (
387
+ self._load_oauth_states_from_file_handle(file_handle)
388
+ )
389
+ result, mutated = mutator(oauth_states)
390
+ if cleaned_expired or mutated:
391
+ self._write_oauth_states_to_file_handle(file_handle, oauth_states)
392
+ return result, oauth_states
393
+ finally:
394
+ _unlock_file(file_handle)
395
+
396
+ def _persist_oauth_state_to_shared_store(
397
+ self, state: str, state_info: Dict[str, Any]
398
+ ) -> None:
399
+ def mutator(
400
+ oauth_states: Dict[str, Dict[str, Any]],
401
+ ) -> Tuple[Optional[Dict[str, Any]], bool]:
402
+ oauth_states[state] = state_info
403
+ return None, True
404
+
405
+ self._update_shared_oauth_states(mutator)
406
+
407
+ def _pop_oauth_state_from_shared_store(
408
+ self, state: str
409
+ ) -> Optional[Dict[str, Any]]:
410
+ def mutator(
411
+ oauth_states: Dict[str, Dict[str, Any]],
412
+ ) -> Tuple[Optional[Dict[str, Any]], bool]:
413
+ state_info = oauth_states.pop(state, None)
414
+ return state_info, state_info is not None
415
+
416
+ result, _ = self._update_shared_oauth_states(mutator)
417
+ return result
418
+
419
+ def _consume_latest_oauth_state_from_shared_store(
420
+ self,
421
+ session_id: Optional[str] = None,
422
+ allow_any_session: bool = False,
423
+ ) -> Optional[Tuple[str, Dict[str, Any]]]:
424
+ def mutator(
425
+ oauth_states: Dict[str, Dict[str, Any]],
426
+ ) -> Tuple[Optional[Tuple[str, Dict[str, Any]]], bool]:
427
+ matching_states = [
428
+ state
429
+ for state, state_info in oauth_states.items()
430
+ if (
431
+ (allow_any_session and session_id is None)
432
+ or state_info.get("session_id") == session_id
433
+ )
434
+ ]
435
+ if not matching_states:
436
+ return None, False
437
+
438
+ latest_state = max(
439
+ matching_states,
440
+ key=lambda s: oauth_states[s].get(
441
+ "created_at",
442
+ datetime.min.replace(tzinfo=timezone.utc),
443
+ ),
444
+ )
445
+ return (latest_state, oauth_states.pop(latest_state)), True
446
+
447
+ result, _ = self._update_shared_oauth_states(mutator)
448
+ return result
449
+
450
+ def _cleanup_expired_oauth_states_locked(self):
451
+ """Remove expired OAuth state entries. Caller must hold lock."""
452
+ now = datetime.now(timezone.utc)
453
+ expired_states = [
454
+ state
455
+ for state, data in self._oauth_states.items()
456
+ if data.get("expires_at") and data["expires_at"] <= now
457
+ ]
458
+ for state in expired_states:
459
+ del self._oauth_states[state]
460
+ logger.debug(
461
+ "Removed expired OAuth state: %s",
462
+ state[:8] if len(state) > 8 else state,
463
+ )
464
+
465
+ def store_oauth_state(
466
+ self,
467
+ state: str,
468
+ session_id: Optional[str] = None,
469
+ expires_in_seconds: int = 600,
470
+ code_verifier: Optional[str] = None,
471
+ user_email: Optional[str] = None,
472
+ expected_user_email: Optional[str] = None,
473
+ enforce_user_email_match: bool = False,
474
+ principal_source: Optional[str] = None,
475
+ ) -> None:
476
+ """Persist an OAuth state value for later validation.
477
+
478
+ Enforced identity bindings are explicit so callback security does not depend on
479
+ process-global configuration at callback time. ``user_email`` is retained only
480
+ for compatibility with state entries created by older releases.
481
+ """
482
+ if not state:
483
+ raise ValueError("OAuth state must be provided")
484
+ if expires_in_seconds < 0:
485
+ raise ValueError("expires_in_seconds must be non-negative")
486
+
487
+ with self._lock:
488
+ self._cleanup_expired_oauth_states_locked()
489
+ now = datetime.now(timezone.utc)
490
+ expiry = now + timedelta(seconds=expires_in_seconds)
491
+ state_info = {
492
+ "session_id": session_id,
493
+ "expires_at": expiry,
494
+ "created_at": now,
495
+ "code_verifier": code_verifier,
496
+ "user_email": user_email,
497
+ "expected_user_email": expected_user_email,
498
+ "enforce_user_email_match": enforce_user_email_match,
499
+ "principal_source": principal_source,
500
+ }
501
+ self._oauth_states[state] = state_info
502
+ self._persist_oauth_state_to_shared_store(state, state_info)
503
+ logger.debug(
504
+ "Stored OAuth state %s (expires at %s)",
505
+ state[:8] if len(state) > 8 else state,
506
+ expiry.isoformat(),
507
+ )
508
+
509
+ def validate_and_consume_oauth_state(
510
+ self,
511
+ state: str,
512
+ session_id: Optional[str] = None,
513
+ ) -> Dict[str, Any]:
514
+ """
515
+ Validate that a state value exists and consume it.
516
+
517
+ Args:
518
+ state: The OAuth state returned by Google.
519
+ session_id: Optional session identifier that initiated the flow.
520
+
521
+ Returns:
522
+ Metadata associated with the state.
523
+
524
+ Raises:
525
+ ValueError: If the state is missing, expired, or does not match the session.
526
+ """
527
+ if not state:
528
+ raise ValueError("Missing OAuth state parameter")
529
+
530
+ with self._lock:
531
+ self._cleanup_expired_oauth_states_locked()
532
+ state_info = self._pop_oauth_state_from_shared_store(state)
533
+ if not state_info:
534
+ self._oauth_states.pop(state, None)
535
+ logger.error(
536
+ "SECURITY: OAuth callback received unknown or expired state"
537
+ )
538
+ raise ValueError("Invalid or expired OAuth state parameter")
539
+
540
+ self._oauth_states.pop(state, None)
541
+ bound_session = state_info.get("session_id")
542
+ if bound_session and session_id and bound_session != session_id:
543
+ logger.error(
544
+ "SECURITY: OAuth state session mismatch (expected %s, got %s)",
545
+ bound_session,
546
+ session_id,
547
+ )
548
+ raise ValueError("OAuth state does not match the initiating session")
549
+
550
+ # State is valid – consume it to prevent reuse
551
+ logger.debug(
552
+ "Validated OAuth state %s",
553
+ state[:8] if len(state) > 8 else state,
554
+ )
555
+ return state_info
556
+
557
+ def consume_latest_oauth_state(
558
+ self,
559
+ initiating_session_id: Optional[str] = None,
560
+ allow_any_session: bool = False,
561
+ ) -> Optional[Dict[str, Any]]:
562
+ """
563
+ Consume and return the most recently created OAuth state.
564
+
565
+ Used as a fallback when the callback URL is missing the state parameter
566
+ (e.g. in stdio mode with certain Google OAuth prompt types).
567
+
568
+ Args:
569
+ initiating_session_id: Optional session identifier that initiated the
570
+ OAuth flow. When provided, only matching shared-store states are
571
+ considered during fallback lookup.
572
+ allow_any_session: When True and no initiating session is available,
573
+ allow fallback lookup across session-bound states. This is only
574
+ safe for local stdio OAuth callbacks.
575
+
576
+ Returns:
577
+ State metadata dict, or None if no states are stored.
578
+ """
579
+ with self._lock:
580
+ self._cleanup_expired_oauth_states_locked()
581
+ shared_state = self._consume_latest_oauth_state_from_shared_store(
582
+ initiating_session_id,
583
+ allow_any_session=allow_any_session,
584
+ )
585
+ if not shared_state:
586
+ self._oauth_states.clear()
587
+ return None
588
+
589
+ latest_state, state_info = shared_state
590
+ self._oauth_states.pop(latest_state, None)
591
+ logger.debug(
592
+ "Consumed latest OAuth state %s as fallback",
593
+ latest_state[:8] if len(latest_state) > 8 else latest_state,
594
+ )
595
+ return state_info
596
+
597
+ def store_session(
598
+ self,
599
+ user_email: str,
600
+ access_token: str,
601
+ refresh_token: Optional[str] = None,
602
+ token_uri: str = "https://oauth2.googleapis.com/token",
603
+ client_id: Optional[str] = None,
604
+ client_secret: Optional[str] = None,
605
+ scopes: Optional[list] = None,
606
+ expiry: Optional[Any] = None,
607
+ session_id: Optional[str] = None,
608
+ mcp_session_id: Optional[str] = None,
609
+ issuer: Optional[str] = None,
610
+ ):
611
+ """
612
+ Store OAuth 2.1 session information.
613
+
614
+ Args:
615
+ user_email: User's email address
616
+ access_token: OAuth 2.1 access token
617
+ refresh_token: OAuth 2.1 refresh token
618
+ token_uri: Token endpoint URI
619
+ client_id: OAuth client ID
620
+ client_secret: OAuth client secret
621
+ scopes: List of granted scopes
622
+ expiry: Token expiry time
623
+ session_id: OAuth 2.1 session ID
624
+ mcp_session_id: FastMCP session ID to map to this user
625
+ issuer: Token issuer (e.g., "https://accounts.google.com")
626
+ """
627
+ # Single-user mode reads credentials directly by email and bypasses the
628
+ # session mapping. Keeping the immutable MCP session binding enabled here
629
+ # turns a successful token refresh for a second account into a false
630
+ # "rebind" error.
631
+ if os.getenv("MCP_SINGLE_USER_MODE") == "1":
632
+ mcp_session_id = None
633
+
634
+ with self._lock:
635
+ bound_user = self._session_auth_binding.get(mcp_session_id)
636
+ if bound_user and bound_user != user_email:
637
+ logger.error(
638
+ f"SECURITY: Attempt to rebind session {mcp_session_id} from {bound_user} to {user_email}"
639
+ )
640
+ raise ValueError(
641
+ f"Session {mcp_session_id} is already bound to a different user"
642
+ )
643
+
644
+ normalized_expiry = _normalize_expiry_to_naive_utc(expiry)
645
+
646
+ # Clean up previous session mappings for this user before storing new one
647
+ old_session = self._sessions.get(user_email)
648
+ if old_session:
649
+ old_mcp_session_id = old_session.get("mcp_session_id")
650
+ old_session_id = old_session.get("session_id")
651
+ # Remove old MCP session mapping if it differs from new one
652
+ if old_mcp_session_id and old_mcp_session_id != mcp_session_id:
653
+ if old_mcp_session_id in self._mcp_session_mapping:
654
+ del self._mcp_session_mapping[old_mcp_session_id]
655
+ logger.debug(
656
+ f"Removed stale MCP session mapping: {old_mcp_session_id}"
657
+ )
658
+ if old_mcp_session_id in self._session_auth_binding:
659
+ del self._session_auth_binding[old_mcp_session_id]
660
+ logger.debug(
661
+ f"Removed stale auth binding: {old_mcp_session_id}"
662
+ )
663
+ # Remove old OAuth session binding if it differs from new one
664
+ if old_session_id and old_session_id != session_id:
665
+ if old_session_id in self._session_auth_binding:
666
+ del self._session_auth_binding[old_session_id]
667
+ logger.debug(
668
+ f"Removed stale OAuth session binding: {old_session_id}"
669
+ )
670
+
671
+ session_info = {
672
+ "access_token": access_token,
673
+ "refresh_token": refresh_token,
674
+ "token_uri": token_uri,
675
+ "client_id": client_id,
676
+ "client_secret": client_secret,
677
+ "scopes": scopes or [],
678
+ "expiry": normalized_expiry,
679
+ "session_id": session_id,
680
+ "mcp_session_id": mcp_session_id,
681
+ "issuer": issuer,
682
+ }
683
+
684
+ self._sessions[user_email] = session_info
685
+
686
+ # Store MCP session mapping if provided
687
+ if mcp_session_id:
688
+ # Create immutable session binding (first binding wins, cannot be changed)
689
+ if mcp_session_id not in self._session_auth_binding:
690
+ self._session_auth_binding[mcp_session_id] = user_email
691
+ # Debug: sessionless (2026-07-28) clients get a new session ID
692
+ # on every request, so this fires per tool call.
693
+ logger.debug(
694
+ f"Created immutable session binding: {mcp_session_id} -> {user_email}"
695
+ )
696
+
697
+ self._mcp_session_mapping[mcp_session_id] = user_email
698
+ logger.debug(
699
+ f"Stored OAuth 2.1 session for {user_email} (session_id: {session_id}, mcp_session_id: {mcp_session_id})"
700
+ )
701
+ else:
702
+ logger.info(
703
+ f"Stored OAuth 2.1 session for {user_email} (session_id: {session_id})"
704
+ )
705
+
706
+ # Also create binding for the OAuth session ID
707
+ if session_id and session_id not in self._session_auth_binding:
708
+ self._session_auth_binding[session_id] = user_email
709
+
710
+ def get_credentials(self, user_email: str) -> Optional[Credentials]:
711
+ """
712
+ Get Google credentials for a user from OAuth 2.1 session.
713
+
714
+ Args:
715
+ user_email: User's email address
716
+
717
+ Returns:
718
+ Google Credentials object or None
719
+ """
720
+ with self._lock:
721
+ session_info = self._sessions.get(user_email)
722
+ if not session_info:
723
+ logger.debug(f"No OAuth 2.1 session found for {user_email}")
724
+ return None
725
+
726
+ try:
727
+ # Create Google credentials from session info
728
+ credentials = Credentials(
729
+ token=session_info["access_token"],
730
+ refresh_token=session_info.get("refresh_token"),
731
+ token_uri=session_info["token_uri"],
732
+ client_id=session_info.get("client_id"),
733
+ client_secret=session_info.get("client_secret"),
734
+ scopes=session_info.get("scopes", []),
735
+ expiry=session_info.get("expiry"),
736
+ )
737
+
738
+ logger.debug(f"Retrieved OAuth 2.1 credentials for {user_email}")
739
+ return credentials
740
+
741
+ except Exception as e:
742
+ logger.error(f"Failed to create credentials for {user_email}: {e}")
743
+ return None
744
+
745
+ def get_credentials_by_mcp_session(
746
+ self, mcp_session_id: str
747
+ ) -> Optional[Credentials]:
748
+ """
749
+ Get Google credentials using FastMCP session ID.
750
+
751
+ Args:
752
+ mcp_session_id: FastMCP session ID
753
+
754
+ Returns:
755
+ Google Credentials object or None
756
+ """
757
+ with self._lock:
758
+ # Look up user email from MCP session mapping
759
+ user_email = self._mcp_session_mapping.get(mcp_session_id)
760
+ if not user_email:
761
+ logger.debug(f"No user mapping found for MCP session {mcp_session_id}")
762
+ return None
763
+
764
+ logger.debug(f"Found user {user_email} for MCP session {mcp_session_id}")
765
+ return self.get_credentials(user_email)
766
+
767
+ def get_credentials_with_validation(
768
+ self,
769
+ requested_user_email: str,
770
+ session_id: Optional[str] = None,
771
+ auth_token_email: Optional[str] = None,
772
+ allow_recent_auth: bool = False,
773
+ ) -> Optional[Credentials]:
774
+ """
775
+ Get Google credentials with session validation.
776
+
777
+ This method ensures that a session can only access credentials for its
778
+ authenticated user, preventing cross-account access.
779
+
780
+ Args:
781
+ requested_user_email: The email of the user whose credentials are requested
782
+ session_id: The current session ID (MCP or OAuth session)
783
+ auth_token_email: Email from the verified auth token (if available)
784
+
785
+ Returns:
786
+ Google Credentials object if validation passes, None otherwise
787
+ """
788
+ with self._lock:
789
+ # Priority 1: Check auth token email (most secure, from verified JWT)
790
+ if auth_token_email:
791
+ if auth_token_email != requested_user_email:
792
+ logger.error(
793
+ f"SECURITY VIOLATION: Token for {auth_token_email} attempted to access "
794
+ f"credentials for {requested_user_email}"
795
+ )
796
+ return None
797
+ # Token email matches, allow access
798
+ return self.get_credentials(requested_user_email)
799
+
800
+ # Priority 2: Check session binding
801
+ if session_id:
802
+ bound_user = self._session_auth_binding.get(session_id)
803
+ if bound_user:
804
+ if bound_user != requested_user_email:
805
+ logger.error(
806
+ f"SECURITY VIOLATION: Session {session_id} (bound to {bound_user}) "
807
+ f"attempted to access credentials for {requested_user_email}"
808
+ )
809
+ return None
810
+ # Session binding matches, allow access
811
+ return self.get_credentials(requested_user_email)
812
+
813
+ # Check if this is an MCP session
814
+ mcp_user = self._mcp_session_mapping.get(session_id)
815
+ if mcp_user:
816
+ if mcp_user != requested_user_email:
817
+ logger.error(
818
+ f"SECURITY VIOLATION: MCP session {session_id} (user {mcp_user}) "
819
+ f"attempted to access credentials for {requested_user_email}"
820
+ )
821
+ return None
822
+ # MCP session matches, allow access
823
+ return self.get_credentials(requested_user_email)
824
+
825
+ # Special case: Allow access if user has recently authenticated (for clients that don't send tokens)
826
+ # CRITICAL SECURITY: This is ONLY allowed in stdio mode, NEVER in OAuth 2.1 mode
827
+ if allow_recent_auth and requested_user_email in self._sessions:
828
+ # Check transport mode to ensure this is only used in stdio
829
+ try:
830
+ from core.config import get_transport_mode
831
+
832
+ transport_mode = get_transport_mode()
833
+ if transport_mode != "stdio":
834
+ logger.error(
835
+ f"SECURITY: Attempted to use allow_recent_auth in {transport_mode} mode. "
836
+ f"This is only allowed in stdio mode!"
837
+ )
838
+ return None
839
+ except Exception as e:
840
+ logger.error(f"Failed to check transport mode: {e}")
841
+ return None
842
+
843
+ logger.info(
844
+ f"Allowing credential access for {requested_user_email} based on recent authentication "
845
+ f"(stdio mode only - client not sending bearer token)"
846
+ )
847
+ return self.get_credentials(requested_user_email)
848
+
849
+ # No session or token info available - deny access for security
850
+ logger.warning(
851
+ f"Credential access denied for {requested_user_email}: No valid session or token"
852
+ )
853
+ return None
854
+
855
+ def get_user_by_mcp_session(self, mcp_session_id: str) -> Optional[str]:
856
+ """
857
+ Get user email by FastMCP session ID.
858
+
859
+ Args:
860
+ mcp_session_id: FastMCP session ID
861
+
862
+ Returns:
863
+ User email or None
864
+ """
865
+ with self._lock:
866
+ return self._mcp_session_mapping.get(mcp_session_id)
867
+
868
+ def get_session_info(self, user_email: str) -> Optional[Dict[str, Any]]:
869
+ """
870
+ Get complete session information including issuer.
871
+
872
+ Args:
873
+ user_email: User's email address
874
+
875
+ Returns:
876
+ Session information dictionary or None
877
+ """
878
+ with self._lock:
879
+ return self._sessions.get(user_email)
880
+
881
+ def remove_session(self, user_email: str):
882
+ """Remove session for a user."""
883
+ with self._lock:
884
+ if user_email in self._sessions:
885
+ # Get session IDs to clean up mappings
886
+ session_info = self._sessions.get(user_email, {})
887
+ mcp_session_id = session_info.get("mcp_session_id")
888
+ session_id = session_info.get("session_id")
889
+
890
+ # Remove from sessions
891
+ del self._sessions[user_email]
892
+
893
+ # Remove from MCP mapping if exists
894
+ if mcp_session_id and mcp_session_id in self._mcp_session_mapping:
895
+ del self._mcp_session_mapping[mcp_session_id]
896
+ # Also remove from auth binding
897
+ if mcp_session_id in self._session_auth_binding:
898
+ del self._session_auth_binding[mcp_session_id]
899
+ logger.info(
900
+ f"Removed OAuth 2.1 session for {user_email} and MCP mapping for {mcp_session_id}"
901
+ )
902
+
903
+ # Remove OAuth session binding if exists
904
+ if session_id and session_id in self._session_auth_binding:
905
+ del self._session_auth_binding[session_id]
906
+
907
+ if not mcp_session_id:
908
+ logger.info(f"Removed OAuth 2.1 session for {user_email}")
909
+
910
+ # Clean up any orphaned mappings that may have accumulated
911
+ self._cleanup_orphaned_mappings_locked()
912
+
913
+ def has_session(self, user_email: str) -> bool:
914
+ """Check if a user has an active session."""
915
+ with self._lock:
916
+ return user_email in self._sessions
917
+
918
+ def has_mcp_session(self, mcp_session_id: str) -> bool:
919
+ """Check if an MCP session has an associated user session."""
920
+ with self._lock:
921
+ return mcp_session_id in self._mcp_session_mapping
922
+
923
+ def get_single_user_email(self) -> Optional[str]:
924
+ """Return the sole authenticated user email when exactly one session exists."""
925
+ with self._lock:
926
+ if len(self._sessions) == 1:
927
+ return next(iter(self._sessions))
928
+ return None
929
+
930
+ def get_stats(self) -> Dict[str, Any]:
931
+ """Get store statistics."""
932
+ with self._lock:
933
+ return {
934
+ "total_sessions": len(self._sessions),
935
+ "users": list(self._sessions.keys()),
936
+ "mcp_session_mappings": len(self._mcp_session_mapping),
937
+ "mcp_sessions": list(self._mcp_session_mapping.keys()),
938
+ }
939
+
940
+ def find_session_id_for_access_token(self, token: str) -> Optional[str]:
941
+ """
942
+ Thread-safe lookup of session ID by access token.
943
+
944
+ Args:
945
+ token: The access token to search for
946
+
947
+ Returns:
948
+ Session ID if found, None otherwise
949
+ """
950
+ with self._lock:
951
+ for user_email, session_info in self._sessions.items():
952
+ if session_info.get("access_token") == token:
953
+ return session_info.get("session_id") or f"bearer_{user_email}"
954
+ return None
955
+
956
+ def _cleanup_orphaned_mappings_locked(self) -> int:
957
+ """Remove orphaned mappings. Caller must hold lock."""
958
+ # Collect valid session IDs and mcp_session_ids from active sessions
959
+ valid_session_ids = set()
960
+ valid_mcp_session_ids = set()
961
+ for session_info in self._sessions.values():
962
+ if session_info.get("session_id"):
963
+ valid_session_ids.add(session_info["session_id"])
964
+ if session_info.get("mcp_session_id"):
965
+ valid_mcp_session_ids.add(session_info["mcp_session_id"])
966
+
967
+ removed = 0
968
+
969
+ # Remove orphaned MCP session mappings
970
+ orphaned_mcp = [
971
+ sid for sid in self._mcp_session_mapping if sid not in valid_mcp_session_ids
972
+ ]
973
+ for sid in orphaned_mcp:
974
+ del self._mcp_session_mapping[sid]
975
+ removed += 1
976
+ logger.debug(f"Removed orphaned MCP session mapping: {sid}")
977
+
978
+ # Remove orphaned auth bindings
979
+ valid_bindings = valid_session_ids | valid_mcp_session_ids
980
+ orphaned_bindings = [
981
+ sid for sid in self._session_auth_binding if sid not in valid_bindings
982
+ ]
983
+ for sid in orphaned_bindings:
984
+ del self._session_auth_binding[sid]
985
+ removed += 1
986
+ logger.debug(f"Removed orphaned auth binding: {sid}")
987
+
988
+ if removed > 0:
989
+ logger.info(f"Cleaned up {removed} orphaned session mappings/bindings")
990
+
991
+ return removed
992
+
993
+ def cleanup_orphaned_mappings(self) -> int:
994
+ """
995
+ Remove orphaned entries from mcp_session_mapping and session_auth_binding.
996
+
997
+ Returns:
998
+ Number of orphaned entries removed
999
+ """
1000
+ with self._lock:
1001
+ return self._cleanup_orphaned_mappings_locked()
1002
+
1003
+
1004
+ # Global instance
1005
+ _global_store = OAuth21SessionStore()
1006
+
1007
+
1008
+ def get_oauth21_session_store() -> OAuth21SessionStore:
1009
+ """Get the global OAuth 2.1 session store."""
1010
+ return _global_store
1011
+
1012
+
1013
+ # =============================================================================
1014
+ # Google Credentials Bridge (absorbed from oauth21_google_bridge.py)
1015
+ # =============================================================================
1016
+
1017
+ # Global auth provider instance (set during server initialization)
1018
+ _auth_provider = None
1019
+
1020
+
1021
+ def set_auth_provider(provider):
1022
+ """Set the global auth provider instance."""
1023
+ global _auth_provider
1024
+ _auth_provider = provider
1025
+ logger.debug("OAuth 2.1 session store configured")
1026
+
1027
+
1028
+ def get_auth_provider():
1029
+ """Get the global auth provider instance."""
1030
+ return _auth_provider
1031
+
1032
+
1033
+ def _resolve_client_credentials() -> Tuple[Optional[str], Optional[str]]:
1034
+ """Resolve OAuth client credentials from the active provider or configuration."""
1035
+ client_id: Optional[str] = None
1036
+ client_secret: Optional[str] = None
1037
+
1038
+ if _auth_provider:
1039
+ client_id = getattr(_auth_provider, "_upstream_client_id", None)
1040
+ secret_obj = getattr(_auth_provider, "_upstream_client_secret", None)
1041
+ if secret_obj is not None:
1042
+ if hasattr(secret_obj, "get_secret_value"):
1043
+ try:
1044
+ client_secret = secret_obj.get_secret_value() # type: ignore[call-arg]
1045
+ except Exception as exc: # pragma: no cover - defensive
1046
+ logger.debug(
1047
+ f"Failed to resolve client secret from provider: {exc}"
1048
+ )
1049
+ elif isinstance(secret_obj, str):
1050
+ client_secret = secret_obj
1051
+
1052
+ if not client_id:
1053
+ try:
1054
+ from auth.oauth_config import get_oauth_config
1055
+
1056
+ cfg = get_oauth_config()
1057
+ client_id = client_id or cfg.client_id
1058
+ client_secret = client_secret or cfg.client_secret
1059
+ except Exception as exc: # pragma: no cover - defensive
1060
+ logger.debug(f"Failed to resolve client credentials from config: {exc}")
1061
+
1062
+ return client_id, client_secret
1063
+
1064
+
1065
+ def _inbound_bearer_token() -> Optional[str]:
1066
+ """Return the raw bearer token from the active HTTP request, if present.
1067
+
1068
+ In OAuth proxy mode this is the FastMCP-issued reference JWT whose ``jti``
1069
+ maps to the upstream Google tokens. It is deliberately distinct from the
1070
+ already-swapped Google access token carried on the validated ``AccessToken``
1071
+ object, which is what makes the upstream refresh token recoverable here.
1072
+ """
1073
+ try:
1074
+ headers = get_http_headers(include={"authorization"})
1075
+ except Exception: # pragma: no cover - no active HTTP request context
1076
+ return None
1077
+
1078
+ auth_header = (headers or {}).get("authorization", "")
1079
+ if auth_header.startswith("Bearer "):
1080
+ return auth_header[7:]
1081
+ return None
1082
+
1083
+
1084
+ async def _build_credentials_from_provider() -> Optional[Credentials]:
1085
+ """Rebuild refreshable Google credentials from the FastMCP OAuth proxy stores.
1086
+
1087
+ FastMCP hands the client an opaque reference JWT and keeps the real Google
1088
+ tokens server-side, keyed by that JWT's ``jti``:
1089
+
1090
+ request JWT ``jti`` -> ``_jti_mapping_store`` -> ``_upstream_token_store``
1091
+
1092
+ Walking that chain yields the upstream access **and refresh** tokens, so the
1093
+ resulting credential can transparently refresh once Google's ~1h access token
1094
+ expires — the missing piece that caused the endless re-auth loop in #886.
1095
+
1096
+ Returns ``None`` when the active provider is not a FastMCP OAuth proxy
1097
+ (external OAuth 2.1 or single-user mode) or when the caller presented a raw
1098
+ Google token directly, so callers fall back to a minimal, non-refreshable
1099
+ credential.
1100
+ """
1101
+ provider = _auth_provider
1102
+ jti_store = getattr(provider, "_jti_mapping_store", None)
1103
+ upstream_store = getattr(provider, "_upstream_token_store", None)
1104
+ if jti_store is None or upstream_store is None:
1105
+ return None
1106
+
1107
+ raw_jwt = _inbound_bearer_token()
1108
+ if not raw_jwt:
1109
+ return None
1110
+
1111
+ try:
1112
+ jti = provider.jwt_issuer.verify_token(raw_jwt).get("jti")
1113
+ if not jti:
1114
+ return None
1115
+ jti_mapping = await jti_store.get(key=jti)
1116
+ if jti_mapping is None:
1117
+ return None
1118
+ upstream = await upstream_store.get(key=jti_mapping.upstream_token_id)
1119
+ if upstream is None:
1120
+ return None
1121
+ except Exception as exc: # pragma: no cover - defensive
1122
+ logger.debug(f"Could not resolve upstream tokens from OAuth proxy: {exc}")
1123
+ return None
1124
+
1125
+ expiry = None
1126
+ if upstream.expires_at:
1127
+ try:
1128
+ expiry = _normalize_expiry_to_naive_utc(
1129
+ datetime.fromtimestamp(upstream.expires_at, tz=timezone.utc)
1130
+ )
1131
+ except Exception: # pragma: no cover - defensive
1132
+ expiry = None
1133
+
1134
+ client_id, client_secret = _resolve_client_credentials()
1135
+ return Credentials(
1136
+ token=upstream.access_token,
1137
+ refresh_token=upstream.refresh_token,
1138
+ token_uri="https://oauth2.googleapis.com/token",
1139
+ client_id=client_id,
1140
+ client_secret=client_secret,
1141
+ scopes=upstream.scope.split() if upstream.scope else None,
1142
+ expiry=expiry,
1143
+ )
1144
+
1145
+
1146
+ async def ensure_session_from_access_token(
1147
+ access_token: AccessToken,
1148
+ user_email: Optional[str],
1149
+ mcp_session_id: Optional[str] = None,
1150
+ ) -> Optional[Credentials]:
1151
+ """Ensure credentials derived from an access token are cached and returned."""
1152
+
1153
+ if not access_token:
1154
+ return None
1155
+
1156
+ email = user_email
1157
+ if not email and getattr(access_token, "claims", None):
1158
+ email = access_token.claims.get("email")
1159
+
1160
+ credentials = await _build_credentials_from_provider()
1161
+ store_expiry: Optional[datetime] = None
1162
+
1163
+ if credentials is None:
1164
+ client_id, client_secret = _resolve_client_credentials()
1165
+ expiry = None
1166
+ expires_at = getattr(access_token, "expires_at", None)
1167
+ if expires_at:
1168
+ try:
1169
+ expiry = datetime.fromtimestamp(expires_at, tz=timezone.utc)
1170
+ except Exception: # pragma: no cover - defensive
1171
+ expiry = None
1172
+
1173
+ normalized_expiry = _normalize_expiry_to_naive_utc(expiry)
1174
+ credentials = Credentials(
1175
+ token=access_token.token,
1176
+ refresh_token=None,
1177
+ token_uri="https://oauth2.googleapis.com/token",
1178
+ client_id=client_id,
1179
+ client_secret=client_secret,
1180
+ scopes=getattr(access_token, "scopes", None),
1181
+ expiry=normalized_expiry,
1182
+ )
1183
+ store_expiry = expiry
1184
+ else:
1185
+ store_expiry = credentials.expiry
1186
+
1187
+ # Skip session storage for external OAuth 2.1 to prevent memory leak from ephemeral tokens
1188
+ if email and not is_external_oauth21_provider():
1189
+ try:
1190
+ store = get_oauth21_session_store()
1191
+ store.store_session(
1192
+ user_email=email,
1193
+ access_token=credentials.token,
1194
+ refresh_token=credentials.refresh_token,
1195
+ token_uri=credentials.token_uri,
1196
+ client_id=credentials.client_id,
1197
+ client_secret=credentials.client_secret,
1198
+ scopes=credentials.scopes,
1199
+ expiry=store_expiry,
1200
+ session_id=f"google_{email}",
1201
+ mcp_session_id=mcp_session_id,
1202
+ issuer="https://accounts.google.com",
1203
+ )
1204
+ except Exception as exc: # pragma: no cover - defensive
1205
+ logger.debug(f"Failed to cache credentials for {email}: {exc}")
1206
+
1207
+ return credentials
1208
+
1209
+
1210
+ def get_credentials_from_token(
1211
+ access_token: str, user_email: Optional[str] = None
1212
+ ) -> Optional[Credentials]:
1213
+ """
1214
+ Convert a bearer token to Google credentials.
1215
+
1216
+ Args:
1217
+ access_token: The bearer token
1218
+ user_email: Optional user email for session lookup
1219
+
1220
+ Returns:
1221
+ Google Credentials object or None
1222
+ """
1223
+ try:
1224
+ store = get_oauth21_session_store()
1225
+
1226
+ # If we have user_email, try to get credentials from store
1227
+ if user_email:
1228
+ credentials = store.get_credentials(user_email)
1229
+ if credentials and credentials.token == access_token:
1230
+ logger.debug(f"Found matching credentials from store for {user_email}")
1231
+ return credentials
1232
+
1233
+ # Provider-managed (OAuth proxy) tokens are resolved to refreshable
1234
+ # credentials during request authentication by
1235
+ # ``ensure_session_from_access_token`` and cached in the session store,
1236
+ # which is the ``store.get_credentials`` lookup above. There is no
1237
+ # token-keyed provider cache to consult here.
1238
+
1239
+ # Create minimal credentials with just the access token
1240
+ # Assume token is valid for 1 hour (typical for Google tokens)
1241
+ expiry = _normalize_expiry_to_naive_utc(
1242
+ datetime.now(timezone.utc) + timedelta(hours=1)
1243
+ )
1244
+ client_id, client_secret = _resolve_client_credentials()
1245
+
1246
+ credentials = Credentials(
1247
+ token=access_token,
1248
+ refresh_token=None,
1249
+ token_uri="https://oauth2.googleapis.com/token",
1250
+ client_id=client_id,
1251
+ client_secret=client_secret,
1252
+ scopes=None,
1253
+ expiry=expiry,
1254
+ )
1255
+
1256
+ logger.debug("Created fallback Google credentials from bearer token")
1257
+ return credentials
1258
+
1259
+ except Exception as e:
1260
+ logger.error(f"Failed to create Google credentials from token: {e}")
1261
+ return None
1262
+
1263
+
1264
+ def store_token_session(
1265
+ token_response: dict, user_email: str, mcp_session_id: Optional[str] = None
1266
+ ) -> str:
1267
+ """
1268
+ Store a token response in the session store.
1269
+
1270
+ Args:
1271
+ token_response: OAuth token response from Google
1272
+ user_email: User's email address
1273
+ mcp_session_id: Optional FastMCP session ID to map to this user
1274
+
1275
+ Returns:
1276
+ Session ID
1277
+ """
1278
+ if not _auth_provider:
1279
+ logger.error("Auth provider not configured")
1280
+ return ""
1281
+
1282
+ try:
1283
+ # Try to get FastMCP session ID from context if not provided
1284
+ if not mcp_session_id:
1285
+ try:
1286
+ from core.context import get_fastmcp_session_id
1287
+
1288
+ mcp_session_id = get_fastmcp_session_id()
1289
+ if mcp_session_id:
1290
+ logger.debug(
1291
+ f"Got FastMCP session ID from context: {mcp_session_id}"
1292
+ )
1293
+ except Exception as e:
1294
+ logger.debug(f"Could not get FastMCP session from context: {e}")
1295
+
1296
+ # Store session in OAuth21SessionStore
1297
+ store = get_oauth21_session_store()
1298
+
1299
+ session_id = f"google_{user_email}"
1300
+ client_id, client_secret = _resolve_client_credentials()
1301
+ scopes = token_response.get("scope", "")
1302
+ scopes_list = scopes.split() if scopes else None
1303
+ expiry = datetime.now(timezone.utc) + timedelta(
1304
+ seconds=token_response.get("expires_in", 3600)
1305
+ )
1306
+
1307
+ store.store_session(
1308
+ user_email=user_email,
1309
+ access_token=token_response.get("access_token"),
1310
+ refresh_token=token_response.get("refresh_token"),
1311
+ token_uri="https://oauth2.googleapis.com/token",
1312
+ client_id=client_id,
1313
+ client_secret=client_secret,
1314
+ scopes=scopes_list,
1315
+ expiry=expiry,
1316
+ session_id=session_id,
1317
+ mcp_session_id=mcp_session_id,
1318
+ issuer="https://accounts.google.com",
1319
+ )
1320
+
1321
+ if mcp_session_id:
1322
+ logger.info(
1323
+ f"Stored token session for {user_email} with MCP session {mcp_session_id}"
1324
+ )
1325
+ else:
1326
+ logger.info(f"Stored token session for {user_email}")
1327
+
1328
+ return session_id
1329
+
1330
+ except Exception as e:
1331
+ logger.error(f"Failed to store token session: {e}")
1332
+ return ""