@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,369 @@
1
+ """
2
+ External OAuth Provider for Google Workspace MCP
3
+
4
+ Extends FastMCP's GoogleProvider to support external OAuth flows where
5
+ access tokens (ya29.*) are issued by external systems and need validation.
6
+
7
+ This provider acts as a Resource Server only - it validates tokens issued by
8
+ Google's Authorization Server but does not issue tokens itself.
9
+ """
10
+
11
+ import asyncio
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ import functools
14
+ import hashlib
15
+ import logging
16
+ import os
17
+ import time
18
+ from typing import Optional
19
+
20
+ from starlette.routing import Route
21
+ from fastmcp.server.auth.providers.google import GoogleProvider
22
+ from fastmcp.server.auth import AccessToken
23
+ from google.oauth2.credentials import Credentials
24
+
25
+ from auth.oauth_types import WorkspaceAccessToken
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Google's OAuth 2.0 Authorization Server
30
+ GOOGLE_ISSUER_URL = "https://accounts.google.com"
31
+
32
+ # Configurable session time in seconds (default: 1 hour, max: 24 hours)
33
+ _DEFAULT_SESSION_TIME = 3600
34
+ _MAX_SESSION_TIME = 86400
35
+
36
+ # Token validation is unauthenticated work and may block for the full Google API
37
+ # socket timeout. Keep it out of asyncio's process-wide default executor so a burst
38
+ # of invalid tokens cannot starve authenticated Google Workspace operations.
39
+ _DEFAULT_TOKEN_VALIDATION_WORKERS = 4
40
+ _TOKEN_VALIDATION_WORKERS_ENV = "WORKSPACE_MCP_TOKEN_VALIDATION_WORKERS"
41
+
42
+ # Validated identities are remembered per token hash for this many seconds.
43
+ # Off by default: a cached token skips the userinfo check until it ages out.
44
+ _TOKEN_VALIDATION_CACHE_TTL_ENV = "WORKSPACE_MCP_TOKEN_VALIDATION_CACHE_TTL"
45
+ _TOKEN_VALIDATION_CACHE_MAX_ENTRIES = 10_000
46
+ # Caps how long a revoked or expired token can keep passing the local check.
47
+ _MAX_TOKEN_VALIDATION_CACHE_TTL = 300
48
+
49
+
50
+ @functools.lru_cache(maxsize=1)
51
+ def get_session_time() -> int:
52
+ """Parse SESSION_TIME from environment with fallback, min/max clamp.
53
+
54
+ Result is cached; changes require a server restart.
55
+ """
56
+ raw = os.getenv("SESSION_TIME", "")
57
+ if not raw:
58
+ return _DEFAULT_SESSION_TIME
59
+ try:
60
+ value = int(raw)
61
+ except ValueError:
62
+ logger.warning(
63
+ "Invalid SESSION_TIME=%r, falling back to %d", raw, _DEFAULT_SESSION_TIME
64
+ )
65
+ return _DEFAULT_SESSION_TIME
66
+ clamped = max(1, min(value, _MAX_SESSION_TIME))
67
+ if clamped != value:
68
+ logger.warning(
69
+ "SESSION_TIME=%d clamped to %d (allowed range: 1–%d)",
70
+ value,
71
+ clamped,
72
+ _MAX_SESSION_TIME,
73
+ )
74
+ return clamped
75
+
76
+
77
+ def get_token_validation_workers() -> int:
78
+ """Parse WORKSPACE_MCP_TOKEN_VALIDATION_WORKERS, defaulting when unset.
79
+
80
+ The pool is shared by every caller of the process, so a gateway fronting
81
+ many users needs more than the default. Invalid values raise instead of
82
+ falling back, so a misconfigured deployment fails at startup.
83
+ """
84
+ raw = os.getenv(_TOKEN_VALIDATION_WORKERS_ENV, "").strip()
85
+ if not raw:
86
+ return _DEFAULT_TOKEN_VALIDATION_WORKERS
87
+ try:
88
+ value = int(raw)
89
+ except ValueError:
90
+ value = 0
91
+ if value < 1:
92
+ raise ValueError(
93
+ f"{_TOKEN_VALIDATION_WORKERS_ENV} must be a positive integer, got {raw!r}"
94
+ )
95
+ return value
96
+
97
+
98
+ def get_token_validation_cache_ttl() -> int:
99
+ """Parse WORKSPACE_MCP_TOKEN_VALIDATION_CACHE_TTL; unset or 0 disables it.
100
+
101
+ Invalid values raise instead of falling back, so a misconfigured deployment
102
+ fails at startup. Values above the maximum are clamped with a warning.
103
+ """
104
+ raw = os.getenv(_TOKEN_VALIDATION_CACHE_TTL_ENV, "").strip()
105
+ if not raw:
106
+ return 0
107
+ try:
108
+ value = int(raw)
109
+ except ValueError:
110
+ value = -1
111
+ if value < 0:
112
+ raise ValueError(
113
+ f"{_TOKEN_VALIDATION_CACHE_TTL_ENV} must be a non-negative integer "
114
+ f"(seconds), got {raw!r}"
115
+ )
116
+ if value > _MAX_TOKEN_VALIDATION_CACHE_TTL:
117
+ logger.warning(
118
+ "%s=%d clamped to %d",
119
+ _TOKEN_VALIDATION_CACHE_TTL_ENV,
120
+ value,
121
+ _MAX_TOKEN_VALIDATION_CACHE_TTL,
122
+ )
123
+ return _MAX_TOKEN_VALIDATION_CACHE_TTL
124
+ return value
125
+
126
+
127
+ class ExternalOAuthProvider(GoogleProvider):
128
+ """
129
+ Extended GoogleProvider that supports validating external Google OAuth access tokens.
130
+
131
+ This provider handles ya29.* access tokens by calling Google's userinfo API,
132
+ while maintaining compatibility with standard JWT ID tokens.
133
+
134
+ Unlike the standard GoogleProvider, this acts as a Resource Server only:
135
+ - Does NOT create /authorize, /token, /register endpoints
136
+ - Only advertises Google's authorization server in metadata
137
+ - Only validates tokens, does not issue them
138
+ """
139
+
140
+ def __init__(
141
+ self,
142
+ client_id: str,
143
+ client_secret: Optional[str] = None,
144
+ resource_server_url: Optional[str] = None,
145
+ token_validation_workers: int = _DEFAULT_TOKEN_VALIDATION_WORKERS,
146
+ token_validation_cache_ttl: int = 0,
147
+ **kwargs,
148
+ ):
149
+ """Initialize and store client credentials for token validation."""
150
+ if token_validation_workers < 1:
151
+ raise ValueError("token_validation_workers must be at least 1")
152
+ if token_validation_cache_ttl < 0:
153
+ raise ValueError("token_validation_cache_ttl must not be negative")
154
+
155
+ self._resource_server_url = resource_server_url
156
+ if resource_server_url and "resource_base_url" not in kwargs:
157
+ kwargs["resource_base_url"] = resource_server_url
158
+ super().__init__(client_id=client_id, client_secret=client_secret, **kwargs)
159
+ # Store credentials as they're not exposed by parent class
160
+ self._client_id = client_id
161
+ self._client_secret = client_secret
162
+ # Store as string - Pydantic validates it when passed to models
163
+ self.resource_server_url = self._resource_server_url
164
+ self._token_validation_executor: Optional[ThreadPoolExecutor] = (
165
+ ThreadPoolExecutor(
166
+ max_workers=token_validation_workers,
167
+ thread_name_prefix="external-token-validation",
168
+ )
169
+ )
170
+ # ThreadPoolExecutor has an unbounded internal queue. Admit no more work
171
+ # than can run immediately so overload fails closed instead of accumulating.
172
+ self._token_validation_slots = asyncio.Semaphore(token_validation_workers)
173
+ # Only touched from the event loop, so no lock is needed. Values are
174
+ # (monotonic expiry, email, sub); the token itself is never stored.
175
+ self._token_validation_cache_ttl = token_validation_cache_ttl
176
+ self._validated_identities: dict[str, tuple[float, str, Optional[str]]] = {}
177
+
178
+ def _cached_identity(self, cache_key: str) -> Optional[tuple[str, Optional[str]]]:
179
+ entry = self._validated_identities.get(cache_key)
180
+ if entry is None:
181
+ return None
182
+ expires_at, email, sub = entry
183
+ if expires_at <= time.monotonic():
184
+ del self._validated_identities[cache_key]
185
+ return None
186
+ return email, sub
187
+
188
+ def _remember_identity(
189
+ self, cache_key: str, email: str, sub: Optional[str]
190
+ ) -> None:
191
+ if not self._token_validation_cache_ttl:
192
+ return
193
+ now = time.monotonic()
194
+ cache = self._validated_identities
195
+ if len(cache) >= _TOKEN_VALIDATION_CACHE_MAX_ENTRIES:
196
+ for key in [
197
+ k for k, (expires_at, _, _) in cache.items() if expires_at <= now
198
+ ]:
199
+ del cache[key]
200
+ if len(cache) >= _TOKEN_VALIDATION_CACHE_MAX_ENTRIES:
201
+ del cache[next(iter(cache))]
202
+ cache[cache_key] = (now + self._token_validation_cache_ttl, email, sub)
203
+
204
+ def _build_access_token(
205
+ self, token: str, email: str, sub: Optional[str]
206
+ ) -> WorkspaceAccessToken:
207
+ scope_list = list(getattr(self, "required_scopes", []) or [])
208
+ return WorkspaceAccessToken(
209
+ token=token,
210
+ scopes=scope_list,
211
+ expires_at=int(time.time()) + get_session_time(),
212
+ claims={"email": email, "sub": sub},
213
+ client_id=self._client_id,
214
+ email=email,
215
+ sub=sub,
216
+ )
217
+
218
+ def close(self) -> None:
219
+ """Stop accepting token-validation work and release executor resources."""
220
+ self._validated_identities.clear()
221
+ executor = self._token_validation_executor
222
+ if executor is None:
223
+ return
224
+ self._token_validation_executor = None
225
+ executor.shutdown(wait=False, cancel_futures=True)
226
+
227
+ async def verify_token(self, token: str) -> Optional[AccessToken]:
228
+ """
229
+ Verify a token - supports both JWT ID tokens and ya29.* access tokens.
230
+
231
+ For ya29.* access tokens (issued externally), validates by calling
232
+ Google's userinfo API. For JWT tokens, delegates to parent class.
233
+
234
+ Args:
235
+ token: Token string to verify (JWT or ya29.* access token)
236
+
237
+ Returns:
238
+ AccessToken object if valid, None otherwise
239
+ """
240
+ # For ya29.* access tokens, validate using Google's userinfo API
241
+ if token.startswith("ya29."):
242
+ logger.debug("Validating external Google OAuth access token")
243
+
244
+ cache_key = hashlib.sha256(token.encode()).hexdigest()
245
+ cached = self._cached_identity(cache_key)
246
+ if cached is not None:
247
+ return self._build_access_token(token, *cached)
248
+
249
+ try:
250
+ from auth.google_auth import get_user_info
251
+
252
+ # Create minimal Credentials object for userinfo API call
253
+ credentials = Credentials(
254
+ token=token,
255
+ token_uri="https://oauth2.googleapis.com/token",
256
+ client_id=self._client_id,
257
+ client_secret=self._client_secret,
258
+ )
259
+
260
+ # Validate token by calling userinfo API. This is deliberately
261
+ # isolated from asyncio's default executor, which handles the
262
+ # authenticated Google Workspace API calls throughout the server.
263
+ if self._token_validation_slots.locked():
264
+ logger.warning(
265
+ "External token validation capacity exhausted; rejecting token"
266
+ )
267
+ return None
268
+
269
+ await self._token_validation_slots.acquire()
270
+ executor = self._token_validation_executor
271
+ if executor is None:
272
+ self._token_validation_slots.release()
273
+ logger.warning(
274
+ "External token validation requested after provider shutdown"
275
+ )
276
+ return None
277
+
278
+ try:
279
+ validation_future = asyncio.get_running_loop().run_in_executor(
280
+ executor,
281
+ functools.partial(
282
+ get_user_info, credentials, skip_valid_check=True
283
+ ),
284
+ )
285
+ except Exception:
286
+ self._token_validation_slots.release()
287
+ raise
288
+
289
+ # Shield the worker future so request cancellation does not mark it
290
+ # complete and release the slot while its HTTPS call is still running.
291
+ # Release inline once the worker is done rather than relying on the
292
+ # event loop running a done callback before this coroutine resumes.
293
+ try:
294
+ user_info = await asyncio.shield(validation_future)
295
+ finally:
296
+ if validation_future.done():
297
+ self._token_validation_slots.release()
298
+ else:
299
+ validation_future.add_done_callback(
300
+ lambda _: self._token_validation_slots.release()
301
+ )
302
+
303
+ if user_info and user_info.get("email"):
304
+ logger.info(
305
+ f"Validated external access token for: {user_info['email']}"
306
+ )
307
+ access_token = self._build_access_token(
308
+ token, user_info["email"], user_info.get("id")
309
+ )
310
+ if self._token_validation_executor is not None:
311
+ self._remember_identity(
312
+ cache_key, access_token.email, access_token.sub
313
+ )
314
+ return access_token
315
+ else:
316
+ logger.error("Could not get user info from access token")
317
+ return None
318
+
319
+ except Exception as e:
320
+ logger.error(f"Error validating external access token: {e}")
321
+ return None
322
+
323
+ # For JWT tokens, use parent class implementation
324
+ return await super().verify_token(token)
325
+
326
+ def get_routes(self, mcp_path: str | None = None) -> list[Route]:
327
+ """
328
+ Get OAuth routes for external provider mode.
329
+
330
+ Returns only protected resource metadata routes that point to Google
331
+ as the authorization server. Does not create authorization server routes
332
+ (/authorize, /token, etc.) since tokens are issued by Google directly.
333
+
334
+ Args:
335
+ mcp_path: Path where FastMCP mounts the protected MCP endpoint.
336
+
337
+ Returns:
338
+ List of routes - only protected resource metadata
339
+ """
340
+ from mcp.server.auth.routes import create_protected_resource_routes
341
+
342
+ if not self.resource_server_url:
343
+ logger.warning(
344
+ "ExternalOAuthProvider: resource_server_url not set, no routes created"
345
+ )
346
+ return []
347
+
348
+ self.set_mcp_path(mcp_path)
349
+ resource_url = self._get_resource_url(mcp_path)
350
+ if not resource_url:
351
+ logger.warning(
352
+ "ExternalOAuthProvider: protected resource URL could not be resolved"
353
+ )
354
+ return []
355
+
356
+ # Create protected resource routes that point to Google as the authorization server
357
+ # Pass strings directly - Pydantic validates them during model construction
358
+ protected_routes = create_protected_resource_routes(
359
+ resource_url=resource_url,
360
+ authorization_servers=[GOOGLE_ISSUER_URL],
361
+ scopes_supported=self.required_scopes,
362
+ resource_name="Google Workspace MCP",
363
+ resource_documentation=None,
364
+ )
365
+
366
+ logger.info(
367
+ f"ExternalOAuthProvider: Created protected resource routes pointing to {GOOGLE_ISSUER_URL}"
368
+ )
369
+ return protected_routes
@@ -0,0 +1,164 @@
1
+ """
2
+ Trusted-gateway identity verification.
3
+
4
+ When an MCP-aware reverse proxy fronts this server, it authenticates the user and
5
+ attaches a SIGNED identity assertion (a JWT) to every upstream request. This module
6
+ verifies that assertion against the proxy's JWKS and returns the verified claims
7
+ (notably the user's email), so the asserted identity can be used as the per-request
8
+ principal — without this server terminating MCP OAuth itself.
9
+
10
+ Provider-agnostic: works with any proxy that injects a JWKS-verifiable JWT identity
11
+ header — e.g. Pomerium (x-pomerium-jwt-assertion, ES256), oauth2-proxy, Cloudflare
12
+ Access (cf-access-jwt-assertion, RS256), Istio/Envoy, Traefik ForwardAuth. The header
13
+ name, signing algorithm(s), JWKS URL, and optional issuer/audience are all configurable
14
+ (see auth.oauth_config); defaults target Pomerium.
15
+
16
+ Security: the assertion is verified cryptographically (signature + expiry, and optional
17
+ issuer/audience). An unverified or malformed assertion yields None — callers must treat
18
+ that as "no identity" (fail closed), never as a trusted user.
19
+ """
20
+
21
+ import logging
22
+ from typing import Any, Optional
23
+
24
+ import jwt
25
+ from jwt import PyJWKClient
26
+ from pydantic.networks import validate_email
27
+
28
+ from auth.oauth_config import get_oauth_config
29
+ from auth.request_identity import get_request_identity
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ class GatewayIdentityError(Exception):
35
+ """Raised when a request lacks a valid trusted-gateway identity."""
36
+
37
+
38
+ def normalize_principal_email(value: Any) -> Optional[str]:
39
+ """Return the canonical form used for gateway principals and credential keys."""
40
+ if not isinstance(value, str):
41
+ return None
42
+ value = value.strip()
43
+ if not value:
44
+ return None
45
+ try:
46
+ _, canonical_email = validate_email(value)
47
+ except ValueError:
48
+ return None
49
+ return canonical_email.lower()
50
+
51
+
52
+ def require_gateway_principal(authenticated_user: Any, authenticated_via: Any) -> str:
53
+ """Return a canonical principal only when it came from gateway verification."""
54
+ email = normalize_principal_email(authenticated_user)
55
+ if authenticated_via != "gateway_assertion" or not email:
56
+ raise GatewayIdentityError(
57
+ "Trusted-gateway mode requires a request-scoped verified gateway principal"
58
+ )
59
+ return email
60
+
61
+
62
+ async def get_verified_gateway_principal(context=None) -> str:
63
+ """Resolve the authoritative gateway principal from the active FastMCP request."""
64
+ identity = await get_request_identity(context)
65
+ if identity is None:
66
+ raise GatewayIdentityError(
67
+ "Trusted-gateway principal is unavailable outside an MCP request"
68
+ )
69
+
70
+ return require_gateway_principal(identity.email, identity.via)
71
+
72
+
73
+ # PyJWKClient caches fetched keys (and refreshes on unknown kid). Cache one client per
74
+ # JWKS URL for the process lifetime.
75
+ _jwks_clients: dict[str, PyJWKClient] = {}
76
+
77
+
78
+ def _get_jwks_client(jwks_url: str) -> PyJWKClient:
79
+ client = _jwks_clients.get(jwks_url)
80
+ if client is None:
81
+ # PyJWKClient keeps fetched signing keys in-memory and re-fetches when it sees an
82
+ # unknown kid (key rotation), so this is safe to hold for the process lifetime.
83
+ client = PyJWKClient(jwks_url, cache_keys=True)
84
+ _jwks_clients[jwks_url] = client
85
+ return client
86
+
87
+
88
+ def verify_gateway_assertion(token: str) -> Optional[dict]:
89
+ """
90
+ Verify a trusted-gateway identity-assertion JWT and return its claims.
91
+
92
+ Args:
93
+ token: the raw JWT from the assertion header.
94
+
95
+ Returns:
96
+ The verified claims dict (includes "email"/"sub") on success, else None.
97
+ """
98
+ if not token:
99
+ return None
100
+
101
+ config = get_oauth_config()
102
+ jwks_url = config.gateway_identity_jwks_url
103
+ if not jwks_url:
104
+ logger.error(
105
+ "verify_gateway_assertion called but GATEWAY_IDENTITY_JWKS_URL is unset"
106
+ )
107
+ return None
108
+ audience = config.gateway_identity_audience
109
+ if not audience:
110
+ logger.error(
111
+ "verify_gateway_assertion called but GATEWAY_IDENTITY_AUDIENCE is unset"
112
+ )
113
+ return None
114
+
115
+ try:
116
+ signing_key = _get_jwks_client(jwks_url).get_signing_key_from_jwt(token)
117
+
118
+ decode_kwargs: dict = {
119
+ # Pin to the configured algorithm(s) so a malicious token can't downgrade to
120
+ # "alg: none" or trigger an HMAC/asymmetric confusion attack.
121
+ "algorithms": config.gateway_identity_algorithms,
122
+ # Require expiry and audience; issuer is additionally enforced when configured.
123
+ "options": {
124
+ "require": ["exp"],
125
+ "verify_aud": True,
126
+ },
127
+ "audience": audience,
128
+ }
129
+ if config.gateway_identity_issuer:
130
+ decode_kwargs["issuer"] = config.gateway_identity_issuer
131
+
132
+ claims = jwt.decode(token, signing_key.key, **decode_kwargs)
133
+ return claims
134
+
135
+ except jwt.PyJWTError as e:
136
+ # Invalid signature / expired / wrong aud-iss / unknown kid, etc.
137
+ logger.warning(
138
+ "SECURITY: rejected gateway identity assertion (%s: %s)",
139
+ type(e).__name__,
140
+ e,
141
+ )
142
+ return None
143
+ except Exception as e: # noqa: BLE001 - JWKS fetch / network / unexpected
144
+ logger.error(
145
+ "Error verifying gateway identity assertion (%s: %s)",
146
+ type(e).__name__,
147
+ e,
148
+ )
149
+ return None
150
+
151
+
152
+ def extract_email_from_assertion(token: str) -> Optional[str]:
153
+ """Verify the assertion and return the lowercased email claim, or None."""
154
+ claims = verify_gateway_assertion(token)
155
+ if not claims:
156
+ return None
157
+ email = normalize_principal_email(claims.get("email"))
158
+ if not email:
159
+ logger.warning(
160
+ "SECURITY: verified gateway assertion has no usable 'email' claim (sub=%s)",
161
+ claims.get("sub"),
162
+ )
163
+ return None
164
+ return email