@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -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,693 @@
1
+ """
2
+ OAuth Configuration Management
3
+
4
+ This module centralizes OAuth-related configuration to eliminate hardcoded values
5
+ scattered throughout the codebase. It provides environment variable support and
6
+ sensible defaults for all OAuth-related settings.
7
+
8
+ Supports both OAuth 2.0 and OAuth 2.1 with automatic client capability detection.
9
+ """
10
+
11
+ import logging
12
+ import os
13
+ from ipaddress import ip_address
14
+ from threading import RLock
15
+ from urllib.parse import urlparse
16
+ from typing import List, Optional, Dict, Any
17
+
18
+ from auth.client_secrets import get_client_secrets_path, load_client_secrets_file
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ _ASYMMETRIC_JWT_ALGORITHM_FAMILIES = {
24
+ "ES": frozenset({"ES256", "ES256K", "ES384", "ES512", "ES521"}),
25
+ "EdDSA": frozenset({"EdDSA"}),
26
+ "PS": frozenset({"PS256", "PS384", "PS512"}),
27
+ "RS": frozenset({"RS256", "RS384", "RS512"}),
28
+ }
29
+
30
+
31
+ def _is_loopback_host(hostname: Optional[str]) -> bool:
32
+ """Return whether a JWKS hostname is explicitly local-only."""
33
+ if not hostname:
34
+ return False
35
+ if hostname.lower() == "localhost":
36
+ return True
37
+ try:
38
+ return ip_address(hostname).is_loopback
39
+ except ValueError:
40
+ return False
41
+
42
+
43
+ def _is_secure_gateway_jwks_url(url: str) -> bool:
44
+ """Require HTTPS except for explicit HTTP loopback development endpoints."""
45
+ try:
46
+ parsed = urlparse(url)
47
+ hostname = parsed.hostname
48
+ except ValueError:
49
+ return False
50
+ return bool(
51
+ hostname
52
+ and (
53
+ parsed.scheme == "https"
54
+ or (parsed.scheme == "http" and _is_loopback_host(hostname))
55
+ )
56
+ )
57
+
58
+
59
+ class OAuthConfig:
60
+ """
61
+ Centralized OAuth configuration management.
62
+
63
+ This class eliminates the hardcoded configuration anti-pattern identified
64
+ in the challenge review by providing a single source of truth for all
65
+ OAuth-related configuration values.
66
+ """
67
+
68
+ def __init__(self):
69
+ # Base server configuration
70
+ self.base_uri = os.getenv("WORKSPACE_MCP_BASE_URI", "http://localhost")
71
+ if os.getenv("WORKSPACE_MCP_RESOLVED_PORT") == "1":
72
+ self.port = int(os.getenv("WORKSPACE_MCP_PORT", os.getenv("PORT", "8000")))
73
+ else:
74
+ self.port = int(os.getenv("PORT", os.getenv("WORKSPACE_MCP_PORT", "8000")))
75
+ self.base_url = f"{self.base_uri}:{self.port}"
76
+
77
+ # External URL for reverse proxy scenarios
78
+ self.external_url = os.getenv("WORKSPACE_EXTERNAL_URL")
79
+
80
+ # OAuth client configuration. Environment variables take precedence;
81
+ # values missing from the environment fall back to the client secrets file
82
+ # (resolved below, once the OAuth 2.1 flag is known).
83
+ self.client_id = os.getenv("GOOGLE_OAUTH_CLIENT_ID")
84
+ self.client_secret = os.getenv("GOOGLE_OAUTH_CLIENT_SECRET")
85
+ self.client_secrets_file: Optional[str] = None
86
+
87
+ # Branding for the OAuth consent page. FastMCP's OAuth proxy renders the
88
+ # server's name / icon / website on the consent screen; these env vars feed
89
+ # those server fields. All optional — unset leaves the upstream defaults.
90
+ self.brand_name = os.getenv("WORKSPACE_MCP_BRAND_NAME")
91
+ self.brand_icon_url = os.getenv("WORKSPACE_MCP_BRAND_ICON_URL")
92
+ self.brand_website_url = os.getenv("WORKSPACE_MCP_BRAND_WEBSITE_URL")
93
+
94
+ # OAuth 2.1 configuration
95
+ self.oauth21_enabled = (
96
+ os.getenv("MCP_ENABLE_OAUTH21", "false").lower() == "true"
97
+ )
98
+ self.pkce_required = self.oauth21_enabled # PKCE is mandatory in OAuth 2.1
99
+ self.supported_code_challenge_methods = (
100
+ ["S256", "plain"] if not self.oauth21_enabled else ["S256"]
101
+ )
102
+
103
+ # External OAuth 2.1 provider configuration. Evaluated before client
104
+ # secrets resolution so it can relax the startup requirement below: in
105
+ # external-provider mode the Google provider is suppressed, so an
106
+ # unreadable GOOGLE_CLIENT_SECRET_PATH is merely logged.
107
+ self.external_oauth21_provider = (
108
+ os.getenv("EXTERNAL_OAUTH21_PROVIDER", "false").lower() == "true"
109
+ )
110
+ if self.external_oauth21_provider and not self.oauth21_enabled:
111
+ raise ValueError(
112
+ "EXTERNAL_OAUTH21_PROVIDER requires MCP_ENABLE_OAUTH21=true"
113
+ )
114
+
115
+ # Only OAuth 2.1 needs client credentials resolved at startup, so an
116
+ # unusable configured path is fatal there and merely logged in the modes
117
+ # that resolve credentials lazily (stdio, service account, legacy 2.0).
118
+ # External-provider mode also suppresses the Google provider, so it does
119
+ # not require readable client secrets either.
120
+ self._apply_client_secrets_file_fallback(
121
+ required=self.oauth21_enabled and not self.external_oauth21_provider
122
+ )
123
+
124
+ # Trusted-gateway identity (provider-agnostic).
125
+ # An MCP-aware reverse proxy (e.g. Pomerium, oauth2-proxy, Cloudflare Access,
126
+ # Istio/Envoy, Traefik ForwardAuth) authenticates the user and injects a SIGNED
127
+ # identity assertion (a JWT) on every upstream request. This server verifies that
128
+ # assertion against the proxy's JWKS and uses the asserted email as the per-request
129
+ # principal — WITHOUT terminating MCP OAuth itself (MCP_ENABLE_OAUTH21 stays off), so
130
+ # it composes with the proxy instead of fighting it for the single MCP auth handshake.
131
+ # Credentials are still the legacy per-user Google grants (keyed by email); the asserted
132
+ # identity just selects/locks which user's grant a request may use (true per-user isolation).
133
+ # Defaults target Pomerium; override the header/algorithm for other providers.
134
+ self.trust_gateway_identity = (
135
+ os.getenv("TRUST_GATEWAY_IDENTITY", "false").lower() == "true"
136
+ )
137
+ self.gateway_identity_jwks_url = (
138
+ os.getenv("GATEWAY_IDENTITY_JWKS_URL", "").strip() or None
139
+ )
140
+ # Header carrying the signed assertion (default: Pomerium's x-pomerium-jwt-assertion;
141
+ # e.g. cf-access-jwt-assertion for Cloudflare Access).
142
+ self.gateway_identity_header = (
143
+ os.getenv("GATEWAY_IDENTITY_HEADER", "x-pomerium-jwt-assertion")
144
+ .strip()
145
+ .lower()
146
+ )
147
+ # Allowed signing algorithm(s), comma-separated (default ES256 — Pomerium; use
148
+ # RS256 for Cloudflare Access, etc.). Pinned to block alg-confusion/none attacks.
149
+ self.gateway_identity_algorithms = [
150
+ a.strip()
151
+ for a in os.getenv("GATEWAY_IDENTITY_ALGORITHMS", "ES256").split(",")
152
+ if a.strip()
153
+ ]
154
+ # Audience binds assertions to this relying party and is mandatory. Issuer
155
+ # pinning remains optional for gateways whose JWKS URL is the trust boundary.
156
+ self.gateway_identity_issuer = (
157
+ os.getenv("GATEWAY_IDENTITY_ISSUER", "").strip() or None
158
+ )
159
+ self.gateway_identity_audience = (
160
+ os.getenv("GATEWAY_IDENTITY_AUDIENCE", "").strip() or None
161
+ )
162
+ if self.trust_gateway_identity:
163
+ if self.oauth21_enabled:
164
+ raise ValueError(
165
+ "TRUST_GATEWAY_IDENTITY is incompatible with MCP_ENABLE_OAUTH21=true. "
166
+ "In trusted-gateway mode the proxy owns the MCP handshake; keep "
167
+ "MCP_ENABLE_OAUTH21=false."
168
+ )
169
+ if not self.gateway_identity_jwks_url:
170
+ raise ValueError(
171
+ "TRUST_GATEWAY_IDENTITY=true requires GATEWAY_IDENTITY_JWKS_URL "
172
+ "(the gateway's JWKS endpoint used to verify the identity assertion)."
173
+ )
174
+ if not _is_secure_gateway_jwks_url(self.gateway_identity_jwks_url):
175
+ raise ValueError(
176
+ "GATEWAY_IDENTITY_JWKS_URL must use HTTPS; HTTP is permitted "
177
+ "only for loopback development endpoints."
178
+ )
179
+ if not self.gateway_identity_algorithms:
180
+ raise ValueError(
181
+ "TRUST_GATEWAY_IDENTITY=true requires GATEWAY_IDENTITY_ALGORITHMS "
182
+ "to list at least one signing algorithm (e.g. ES256)."
183
+ )
184
+ algorithm_families = {
185
+ family
186
+ for family, algorithms in _ASYMMETRIC_JWT_ALGORITHM_FAMILIES.items()
187
+ if any(
188
+ algorithm in algorithms
189
+ for algorithm in self.gateway_identity_algorithms
190
+ )
191
+ }
192
+ allowed_algorithms = set().union(
193
+ *_ASYMMETRIC_JWT_ALGORITHM_FAMILIES.values()
194
+ )
195
+ invalid_algorithms = [
196
+ algorithm
197
+ for algorithm in self.gateway_identity_algorithms
198
+ if algorithm not in allowed_algorithms
199
+ ]
200
+ if invalid_algorithms:
201
+ raise ValueError(
202
+ "GATEWAY_IDENTITY_ALGORITHMS must contain only supported "
203
+ "asymmetric JWT algorithms."
204
+ )
205
+ if len(algorithm_families) != 1:
206
+ raise ValueError(
207
+ "GATEWAY_IDENTITY_ALGORITHMS must use a single asymmetric "
208
+ "JWT algorithm family."
209
+ )
210
+ if not self.gateway_identity_header:
211
+ raise ValueError(
212
+ "TRUST_GATEWAY_IDENTITY=true requires a non-empty "
213
+ "GATEWAY_IDENTITY_HEADER."
214
+ )
215
+ if not self.gateway_identity_audience:
216
+ raise ValueError(
217
+ "TRUST_GATEWAY_IDENTITY=true requires GATEWAY_IDENTITY_AUDIENCE "
218
+ "(the audience that identifies this MCP deployment)."
219
+ )
220
+
221
+ # Stateless mode configuration
222
+ self.stateless_mode = (
223
+ os.getenv("WORKSPACE_MCP_STATELESS_MODE", "false").lower() == "true"
224
+ )
225
+ if self.stateless_mode and not self.oauth21_enabled:
226
+ raise ValueError(
227
+ "WORKSPACE_MCP_STATELESS_MODE requires MCP_ENABLE_OAUTH21=true"
228
+ )
229
+
230
+ # Service account (domain-wide delegation) configuration
231
+ self.service_account_key_file = os.getenv("GOOGLE_SERVICE_ACCOUNT_KEY_FILE")
232
+ self.service_account_key_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_KEY_JSON")
233
+ if self.service_account_key_file and self.service_account_key_json:
234
+ raise ValueError(
235
+ "Only one service account key source may be provided. "
236
+ "Set either GOOGLE_SERVICE_ACCOUNT_KEY_FILE or "
237
+ "GOOGLE_SERVICE_ACCOUNT_KEY_JSON, not both."
238
+ )
239
+ self.service_account_enabled = bool(
240
+ self.service_account_key_file or self.service_account_key_json
241
+ )
242
+ if self.service_account_enabled and self.oauth21_enabled:
243
+ raise ValueError(
244
+ "Service account mode is incompatible with OAuth 2.1 mode. "
245
+ "Set GOOGLE_SERVICE_ACCOUNT_KEY_FILE or GOOGLE_SERVICE_ACCOUNT_KEY_JSON, "
246
+ "but not MCP_ENABLE_OAUTH21=true."
247
+ )
248
+
249
+ # Optional per-request impersonation domain allowlist for service accounts.
250
+ _raw_domains = os.getenv("DWD_ALLOWED_DOMAINS", "")
251
+ self.dwd_allowed_domains: List[str] = (
252
+ [d.strip().lower() for d in _raw_domains.split(",") if d.strip()]
253
+ if self.service_account_enabled and _raw_domains
254
+ else []
255
+ )
256
+ # Transport mode (will be set at runtime)
257
+ self._transport_mode = "stdio" # Default
258
+
259
+ # Redirect URI configuration
260
+ self.redirect_uri = self._get_redirect_uri()
261
+ self.redirect_path = self._get_redirect_path(self.redirect_uri)
262
+
263
+ def _apply_client_secrets_file_fallback(self, required: bool) -> None:
264
+ """Fill missing client credentials from the client secrets file.
265
+
266
+ Environment variables always take precedence; the file
267
+ (GOOGLE_CLIENT_SECRET_PATH, the legacy GOOGLE_CLIENT_SECRETS alias, or
268
+ <repo root>/client_secret.json) is only consulted for values the
269
+ environment does not provide, so a fully env-configured client never
270
+ touches the file.
271
+
272
+ Args:
273
+ required: Whether startup depends on these credentials. When True, a
274
+ file at an explicitly configured path that cannot be read is
275
+ fatal; otherwise the failure is logged and startup continues.
276
+ """
277
+ if self.client_id and self.client_secret:
278
+ return
279
+
280
+ path = get_client_secrets_path()
281
+ explicit = bool(
282
+ os.getenv("GOOGLE_CLIENT_SECRET_PATH") or os.getenv("GOOGLE_CLIENT_SECRETS")
283
+ )
284
+ try:
285
+ section = load_client_secrets_file(path)
286
+ except (OSError, ValueError) as exc:
287
+ if explicit and required:
288
+ raise ValueError(
289
+ f"Failed to load client secrets file {path}: {exc}. Set a valid "
290
+ "GOOGLE_CLIENT_SECRET_PATH, or provide GOOGLE_OAUTH_CLIENT_ID and "
291
+ "GOOGLE_OAUTH_CLIENT_SECRET environment variables."
292
+ ) from exc
293
+ log = logger.warning if explicit else logger.debug
294
+ log("Ignoring client secrets file %s: %s", path, exc)
295
+ return
296
+
297
+ file_client_id = section.get("client_id") or None
298
+ file_client_secret = section.get("client_secret") or None
299
+ if self.client_id and file_client_id and file_client_id != self.client_id:
300
+ # The file describes a different OAuth client, so its secret cannot
301
+ # authenticate the configured client id. Pairing them would turn a
302
+ # public client into a confidential one that Google always rejects.
303
+ logger.warning(
304
+ "Ignoring client secrets file %s: it configures client id %s, not the "
305
+ "GOOGLE_OAUTH_CLIENT_ID this server runs as.",
306
+ path,
307
+ file_client_id,
308
+ )
309
+ return
310
+
311
+ loaded = False
312
+ if not self.client_id and file_client_id:
313
+ self.client_id = file_client_id
314
+ loaded = True
315
+ if not self.client_secret and file_client_secret:
316
+ self.client_secret = file_client_secret
317
+ loaded = True
318
+ if loaded:
319
+ self.client_secrets_file = path
320
+ logger.info("Loaded OAuth client credentials from file: %s", path)
321
+
322
+ def _get_redirect_uri(self) -> str:
323
+ """
324
+ Get the OAuth redirect URI, supporting reverse proxy configurations.
325
+
326
+ Returns:
327
+ The configured redirect URI
328
+ """
329
+ explicit_uri = os.getenv("GOOGLE_OAUTH_REDIRECT_URI")
330
+ if explicit_uri:
331
+ return explicit_uri
332
+ return f"{self.base_url}/oauth2callback"
333
+
334
+ @staticmethod
335
+ def _get_redirect_path(uri: str) -> str:
336
+ """Extract the redirect path from a full redirect URI."""
337
+ parsed = urlparse(uri)
338
+ if parsed.scheme or parsed.netloc:
339
+ path = parsed.path or "/oauth2callback"
340
+ else:
341
+ # If the value was already a path, ensure it starts with '/'
342
+ path = uri if uri.startswith("/") else f"/{uri}"
343
+ return path or "/oauth2callback"
344
+
345
+ def is_public_client(self) -> bool:
346
+ """Return True when only a client_id is configured (no client_secret)."""
347
+ return bool(self.client_id and not self.client_secret)
348
+
349
+ def get_redirect_uris(self) -> List[str]:
350
+ """
351
+ Get all valid OAuth redirect URIs.
352
+
353
+ Returns:
354
+ List of all supported redirect URIs
355
+ """
356
+ uris = []
357
+
358
+ # Primary redirect URI
359
+ uris.append(self.redirect_uri)
360
+
361
+ # Custom redirect URIs from environment
362
+ custom_uris = os.getenv("OAUTH_CUSTOM_REDIRECT_URIS")
363
+ if custom_uris:
364
+ uris.extend([uri.strip() for uri in custom_uris.split(",")])
365
+
366
+ # Remove duplicates while preserving order
367
+ return list(dict.fromkeys(uris))
368
+
369
+ def get_allowed_origins(self) -> List[str]:
370
+ """
371
+ Get allowed CORS origins for OAuth endpoints.
372
+
373
+ Returns:
374
+ List of allowed origins for CORS
375
+ """
376
+ origins = []
377
+
378
+ # Server's own origin
379
+ origins.append(self.base_url)
380
+
381
+ # VS Code and development origins
382
+ origins.extend(
383
+ [
384
+ "vscode-webview://",
385
+ "https://vscode.dev",
386
+ "https://github.dev",
387
+ ]
388
+ )
389
+
390
+ # Custom origins from environment
391
+ custom_origins = os.getenv("OAUTH_ALLOWED_ORIGINS")
392
+ if custom_origins:
393
+ origins.extend([origin.strip() for origin in custom_origins.split(",")])
394
+
395
+ return list(dict.fromkeys(origins))
396
+
397
+ def is_configured(self) -> bool:
398
+ """
399
+ Check if OAuth is properly configured.
400
+
401
+ Returns:
402
+ True if OAuth client credentials are available
403
+ """
404
+ return bool(self.client_id)
405
+
406
+ def get_oauth_base_url(self) -> str:
407
+ """
408
+ Get OAuth base URL for constructing OAuth endpoints.
409
+
410
+ Uses WORKSPACE_EXTERNAL_URL if set (for reverse proxy scenarios),
411
+ otherwise falls back to constructed base_url with port.
412
+
413
+ Returns:
414
+ Base URL for OAuth endpoints
415
+ """
416
+ if self.external_url:
417
+ return self.external_url
418
+ return self.base_url
419
+
420
+ def validate_redirect_uri(self, uri: str) -> bool:
421
+ """
422
+ Validate if a redirect URI is allowed.
423
+
424
+ Args:
425
+ uri: The redirect URI to validate
426
+
427
+ Returns:
428
+ True if the URI is allowed, False otherwise
429
+ """
430
+ allowed_uris = self.get_redirect_uris()
431
+ return uri in allowed_uris
432
+
433
+ def get_environment_summary(self) -> dict:
434
+ """
435
+ Get a summary of the current OAuth configuration.
436
+
437
+ Returns:
438
+ Dictionary with configuration summary (excluding secrets)
439
+ """
440
+ return {
441
+ "base_url": self.base_url,
442
+ "external_url": self.external_url,
443
+ "effective_oauth_url": self.get_oauth_base_url(),
444
+ "redirect_uri": self.redirect_uri,
445
+ "redirect_path": self.redirect_path,
446
+ "client_configured": bool(self.client_id),
447
+ "client_secret_configured": bool(self.client_secret),
448
+ "public_client": self.is_public_client(),
449
+ "oauth21_enabled": self.oauth21_enabled,
450
+ "external_oauth21_provider": self.external_oauth21_provider,
451
+ "pkce_required": self.pkce_required,
452
+ "service_account_enabled": self.service_account_enabled,
453
+ "transport_mode": self._transport_mode,
454
+ "total_redirect_uris": len(self.get_redirect_uris()),
455
+ "total_allowed_origins": len(self.get_allowed_origins()),
456
+ }
457
+
458
+ def set_transport_mode(self, mode: str) -> None:
459
+ """
460
+ Set the current transport mode for OAuth callback handling.
461
+
462
+ Args:
463
+ mode: Transport mode ("stdio", "streamable-http", etc.)
464
+ """
465
+ self._transport_mode = mode
466
+
467
+ def get_transport_mode(self) -> str:
468
+ """
469
+ Get the current transport mode.
470
+
471
+ Returns:
472
+ Current transport mode
473
+ """
474
+ return self._transport_mode
475
+
476
+ def is_oauth21_enabled(self) -> bool:
477
+ """
478
+ Check if OAuth 2.1 mode is enabled.
479
+
480
+ Returns:
481
+ True if OAuth 2.1 is enabled
482
+ """
483
+ return self.oauth21_enabled
484
+
485
+ def is_external_oauth21_provider(self) -> bool:
486
+ """
487
+ Check if external OAuth 2.1 provider mode is enabled.
488
+
489
+ When enabled, the server expects external OAuth flow with bearer tokens
490
+ in Authorization headers for tool calls. Protocol-level auth is disabled.
491
+
492
+ Returns:
493
+ True if external OAuth 2.1 provider is enabled
494
+ """
495
+ return self.external_oauth21_provider
496
+
497
+ def is_service_account_enabled(self) -> bool:
498
+ """
499
+ Check if service account (domain-wide delegation) mode is enabled.
500
+
501
+ Returns:
502
+ True if service account mode is enabled
503
+ """
504
+ return self.service_account_enabled
505
+
506
+ def detect_oauth_version(self, request_params: Dict[str, Any]) -> str:
507
+ """
508
+ Detect OAuth version based on request parameters.
509
+
510
+ This method implements a conservative detection strategy:
511
+ - Only returns "oauth21" when we have clear indicators
512
+ - Defaults to "oauth20" for backward compatibility
513
+ - Respects the global oauth21_enabled flag
514
+
515
+ Args:
516
+ request_params: Request parameters from authorization or token request
517
+
518
+ Returns:
519
+ "oauth21" or "oauth20" based on detection
520
+ """
521
+ # If OAuth 2.1 is not enabled globally, always return OAuth 2.0
522
+ if not self.oauth21_enabled:
523
+ return "oauth20"
524
+
525
+ # Use the structured type for cleaner detection logic
526
+ from auth.oauth_types import OAuthVersionDetectionParams
527
+
528
+ params = OAuthVersionDetectionParams.from_request(request_params)
529
+
530
+ # Clear OAuth 2.1 indicator: PKCE is present
531
+ if params.has_pkce:
532
+ return "oauth21"
533
+
534
+ # Additional detection: Check if we have an active OAuth 2.1 session
535
+ # This is important for tool calls where PKCE params aren't available
536
+ authenticated_user = request_params.get("authenticated_user")
537
+ if authenticated_user:
538
+ try:
539
+ from auth.oauth21_session_store import get_oauth21_session_store
540
+
541
+ store = get_oauth21_session_store()
542
+ if store.has_session(authenticated_user):
543
+ return "oauth21"
544
+ except (ImportError, AttributeError, RuntimeError):
545
+ pass # Fall back to OAuth 2.0 if session check fails
546
+
547
+ # For public clients in OAuth 2.1 mode, we require PKCE
548
+ # But since they didn't send PKCE, fall back to OAuth 2.0
549
+ # This ensures backward compatibility
550
+
551
+ # Default to OAuth 2.0 for maximum compatibility
552
+ return "oauth20"
553
+
554
+ def get_authorization_server_metadata(
555
+ self, scopes: Optional[List[str]] = None
556
+ ) -> Dict[str, Any]:
557
+ """
558
+ Get OAuth authorization server metadata per RFC 8414.
559
+
560
+ Args:
561
+ scopes: Optional list of supported scopes to include in metadata
562
+
563
+ Returns:
564
+ Authorization server metadata dictionary
565
+ """
566
+ oauth_base = self.get_oauth_base_url()
567
+ metadata = {
568
+ "issuer": "https://accounts.google.com",
569
+ "authorization_endpoint": f"{oauth_base}/oauth2/authorize",
570
+ "token_endpoint": f"{oauth_base}/oauth2/token",
571
+ "registration_endpoint": f"{oauth_base}/oauth2/register",
572
+ "jwks_uri": "https://www.googleapis.com/oauth2/v3/certs",
573
+ "userinfo_endpoint": "https://openidconnect.googleapis.com/v1/userinfo",
574
+ "response_types_supported": ["code", "token"],
575
+ "grant_types_supported": ["authorization_code", "refresh_token"],
576
+ "token_endpoint_auth_methods_supported": (
577
+ ["none"]
578
+ if self.is_public_client()
579
+ else ["client_secret_post", "client_secret_basic"]
580
+ ),
581
+ "code_challenge_methods_supported": self.supported_code_challenge_methods,
582
+ }
583
+
584
+ # Include scopes if provided
585
+ if scopes is not None:
586
+ metadata["scopes_supported"] = scopes
587
+
588
+ # Add OAuth 2.1 specific metadata
589
+ if self.oauth21_enabled:
590
+ metadata["pkce_required"] = True
591
+ # OAuth 2.1 deprecates implicit flow
592
+ metadata["response_types_supported"] = ["code"]
593
+ # OAuth 2.1 requires exact redirect URI matching
594
+ metadata["require_exact_redirect_uri"] = True
595
+
596
+ return metadata
597
+
598
+
599
+ # Global configuration instance with thread-safe access
600
+ _oauth_config = None
601
+ _oauth_config_lock = RLock()
602
+
603
+
604
+ def get_oauth_config() -> OAuthConfig:
605
+ """
606
+ Get the global OAuth configuration instance.
607
+
608
+ Thread-safe singleton accessor.
609
+
610
+ Returns:
611
+ The singleton OAuth configuration instance
612
+ """
613
+ global _oauth_config
614
+ with _oauth_config_lock:
615
+ if _oauth_config is None:
616
+ _oauth_config = OAuthConfig()
617
+ return _oauth_config
618
+
619
+
620
+ def reload_oauth_config() -> OAuthConfig:
621
+ """
622
+ Reload the OAuth configuration from environment variables.
623
+
624
+ Thread-safe reload that prevents races with concurrent access.
625
+
626
+ Returns:
627
+ The reloaded OAuth configuration instance
628
+ """
629
+ global _oauth_config
630
+ with _oauth_config_lock:
631
+ _oauth_config = OAuthConfig()
632
+ return _oauth_config
633
+
634
+
635
+ # Convenience functions for backward compatibility
636
+ def get_oauth_base_url() -> str:
637
+ """Get OAuth base URL."""
638
+ return get_oauth_config().get_oauth_base_url()
639
+
640
+
641
+ def get_redirect_uris() -> List[str]:
642
+ """Get all valid OAuth redirect URIs."""
643
+ return get_oauth_config().get_redirect_uris()
644
+
645
+
646
+ def get_allowed_origins() -> List[str]:
647
+ """Get allowed CORS origins."""
648
+ return get_oauth_config().get_allowed_origins()
649
+
650
+
651
+ def is_oauth_configured() -> bool:
652
+ """Check if OAuth is properly configured."""
653
+ return get_oauth_config().is_configured()
654
+
655
+
656
+ def set_transport_mode(mode: str) -> None:
657
+ """Set the current transport mode."""
658
+ get_oauth_config().set_transport_mode(mode)
659
+
660
+
661
+ def get_transport_mode() -> str:
662
+ """Get the current transport mode."""
663
+ return get_oauth_config().get_transport_mode()
664
+
665
+
666
+ def is_oauth21_enabled() -> bool:
667
+ """Check if OAuth 2.1 is enabled."""
668
+ return get_oauth_config().is_oauth21_enabled()
669
+
670
+
671
+ def get_oauth_redirect_uri() -> str:
672
+ """Get the primary OAuth redirect URI."""
673
+ return get_oauth_config().redirect_uri
674
+
675
+
676
+ def is_stateless_mode() -> bool:
677
+ """Check if stateless mode is enabled."""
678
+ return get_oauth_config().stateless_mode
679
+
680
+
681
+ def is_external_oauth21_provider() -> bool:
682
+ """Check if external OAuth 2.1 provider mode is enabled."""
683
+ return get_oauth_config().is_external_oauth21_provider()
684
+
685
+
686
+ def is_trust_gateway_identity() -> bool:
687
+ """Check if trusted-gateway identity (signed assertion) mode is enabled."""
688
+ return get_oauth_config().trust_gateway_identity
689
+
690
+
691
+ def is_service_account_enabled() -> bool:
692
+ """Check if service account (domain-wide delegation) mode is enabled."""
693
+ return get_oauth_config().is_service_account_enabled()