@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,253 @@
1
+ """
2
+ GCS-backed temporary attachment storage.
3
+
4
+ Alternative to the local-disk ``AttachmentStorage`` for horizontally scaled or
5
+ scale-to-zero HTTP deployments (e.g. Cloud Run), where the built-in
6
+ ``/attachments/{id}`` route may hit a different instance than the one that
7
+ stored the file. Files are staged in a GCS bucket and handed out as V4 signed
8
+ URLs, so the client downloads straight from GCS. This also works in stateless
9
+ mode: stateless refers to credential and session state, not file staging.
10
+
11
+ Enable by setting:
12
+ WORKSPACE_MCP_FILES_GCS_BUCKET=<bucket-name> (required)
13
+ WORKSPACE_MCP_FILES_GCS_PREFIX=<object-prefix> (optional, default "attachments")
14
+
15
+ Object lifetime is left to a bucket lifecycle rule. Without an exported
16
+ private key (e.g. Cloud Run default credentials), URLs are signed through the
17
+ IAM signBlob API, which needs ``roles/iam.serviceAccountTokenCreator`` for the
18
+ runtime service account on itself.
19
+ """
20
+
21
+ import base64
22
+ import logging
23
+ import os
24
+ import threading
25
+ import uuid
26
+ from datetime import datetime, timedelta
27
+ from typing import Dict, Optional
28
+
29
+ import google.auth
30
+ from google.auth.transport.requests import Request
31
+
32
+ from auth.oauth_config import get_transport_mode
33
+ from core.attachment_storage import (
34
+ DEFAULT_EXPIRATION_SECONDS,
35
+ SavedAttachment,
36
+ sanitize_attachment_filename,
37
+ )
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+ _BUCKET_ENV = "WORKSPACE_MCP_FILES_GCS_BUCKET"
42
+ _PREFIX_ENV = "WORKSPACE_MCP_FILES_GCS_PREFIX"
43
+
44
+
45
+ def gcs_files_enabled() -> bool:
46
+ """True when GCS file staging is configured and the transport is not stdio.
47
+
48
+ A stdio client shares the server's filesystem and reads the local path the
49
+ tools hand back, so local disk stays the backend there.
50
+ """
51
+ return bool(os.getenv(_BUCKET_ENV)) and get_transport_mode() != "stdio"
52
+
53
+
54
+ class GCSAttachmentStorage:
55
+ """Stores attachments as GCS objects and serves them via signed URLs.
56
+
57
+ Covers the parts of ``AttachmentStorage`` the tools call, and adds
58
+ ``get_signed_url``. Two methods are deliberately absent: ``sweep_expired``
59
+ and ``cleanup_expired`` delete files from local disk, while GCS objects are
60
+ removed by the bucket's lifecycle rule. ``get_attachment_storage`` only
61
+ sweeps the local backend, so nothing asks this one for them.
62
+
63
+ ``get_attachment_path`` returns ``None`` here: there is no local file. The
64
+ ``/attachments/{id}`` route answers 404 for that, which is correct — with
65
+ GCS the client follows the signed URL instead.
66
+ """
67
+
68
+ def __init__(self) -> None:
69
+ self.bucket_name = os.environ[_BUCKET_ENV]
70
+ prefix = os.getenv(_PREFIX_ENV, "attachments").strip("/")
71
+ self.prefix = f"{prefix}/" if prefix else ""
72
+ self.expiration_seconds = DEFAULT_EXPIRATION_SECONDS
73
+ # file_id -> metadata, kept only until the signed URL lapses: the URL
74
+ # is generated right after save, on the same instance.
75
+ self._metadata: Dict[str, Dict] = {}
76
+ self._metadata_lock = threading.Lock()
77
+ self._client = None
78
+
79
+ def _get_client(self):
80
+ if self._client is None:
81
+ # The [gcs] extra is optional, so import it only once enabled.
82
+ from google.cloud import storage
83
+
84
+ self._client = storage.Client()
85
+ return self._client
86
+
87
+ def _upload_target(self, filename: Optional[str]):
88
+ """Return a fresh file_id, its sanitized name, and the blob to write."""
89
+ file_id = str(uuid.uuid4())
90
+ safe_filename = sanitize_attachment_filename(filename) if filename else file_id
91
+ blob_name = f"{self.prefix}{file_id}/{safe_filename}"
92
+ blob = self._get_client().bucket(self.bucket_name).blob(blob_name)
93
+ # Objects carry user data and are reachable by anyone holding the signed
94
+ # URL, so keep caches out of the path: GCS otherwise defaults unset
95
+ # Cache-Control to "public, max-age=3600", which lets a browser or an
96
+ # intermediary keep the bytes after the URL has expired. Set here rather
97
+ # than at each call site so every upload path inherits it.
98
+ blob.cache_control = "no-store"
99
+ return file_id, safe_filename, blob
100
+
101
+ def _record(
102
+ self,
103
+ file_id: str,
104
+ blob_name: str,
105
+ safe_filename: str,
106
+ filename: Optional[str],
107
+ mime_type: Optional[str],
108
+ size: int,
109
+ ) -> SavedAttachment:
110
+ """Record an uploaded object, dropping entries whose URL has lapsed."""
111
+ now = datetime.now()
112
+ with self._metadata_lock:
113
+ expired = [
114
+ key for key, meta in self._metadata.items() if meta["expires_at"] <= now
115
+ ]
116
+ for key in expired:
117
+ del self._metadata[key]
118
+ self._metadata[file_id] = {
119
+ "blob_name": blob_name,
120
+ "filename": safe_filename,
121
+ "original_filename": filename,
122
+ "mime_type": mime_type or "application/octet-stream",
123
+ "size": size,
124
+ "expires_at": now + timedelta(seconds=self.expiration_seconds),
125
+ }
126
+ path = f"gs://{self.bucket_name}/{blob_name}"
127
+ logger.info(
128
+ f"Saved attachment file_id={file_id} filename={filename or safe_filename} "
129
+ f"({size} bytes) to {path}"
130
+ )
131
+ return SavedAttachment(file_id=file_id, path=path)
132
+
133
+ def save_attachment(
134
+ self,
135
+ base64_data: str,
136
+ filename: Optional[str] = None,
137
+ mime_type: Optional[str] = None,
138
+ ) -> SavedAttachment:
139
+ """Upload a base64-encoded attachment; ``path`` is the ``gs://`` URI."""
140
+ try:
141
+ file_bytes = base64.urlsafe_b64decode(base64_data)
142
+ except Exception as e:
143
+ logger.error(f"Failed to decode base64 attachment data: {e}")
144
+ raise ValueError(f"Invalid base64 data: {e}")
145
+
146
+ return self.save_attachment_bytes(file_bytes, filename, mime_type)
147
+
148
+ def save_attachment_bytes(
149
+ self,
150
+ file_bytes: bytes,
151
+ filename: Optional[str] = None,
152
+ mime_type: Optional[str] = None,
153
+ ) -> SavedAttachment:
154
+ """Upload already-decoded bytes."""
155
+ file_id, safe_filename, blob = self._upload_target(filename)
156
+ blob.upload_from_string(
157
+ file_bytes, content_type=mime_type or "application/octet-stream"
158
+ )
159
+ return self._record(
160
+ file_id, blob.name, safe_filename, filename, mime_type, len(file_bytes)
161
+ )
162
+
163
+ def save_attachment_from_path(
164
+ self,
165
+ src_path: str,
166
+ filename: Optional[str] = None,
167
+ mime_type: Optional[str] = None,
168
+ ) -> SavedAttachment:
169
+ """Stream an already-downloaded file into GCS, then remove the source.
170
+
171
+ The caller hands the file over, so it is removed even if the upload
172
+ fails and must not be reused afterwards.
173
+ """
174
+ file_id, safe_filename, blob = self._upload_target(filename)
175
+ size = os.path.getsize(src_path)
176
+ try:
177
+ blob.upload_from_filename(
178
+ src_path, content_type=mime_type or "application/octet-stream"
179
+ )
180
+ finally:
181
+ try:
182
+ os.unlink(src_path)
183
+ except OSError:
184
+ logger.debug("Could not remove staged source file %s", src_path)
185
+ return self._record(
186
+ file_id, blob.name, safe_filename, filename, mime_type, size
187
+ )
188
+
189
+ def get_attachment_path(self, file_id: str) -> None:
190
+ """Always ``None``: the bytes live in GCS, so the local route answers 404."""
191
+ return None
192
+
193
+ def get_attachment_metadata(self, file_id: str) -> Optional[Dict]:
194
+ """Metadata for an attachment, or None once its URL lifetime has run out.
195
+
196
+ Returns a copy: the caller must not be able to mutate the shared dict,
197
+ and the entry can be evicted between calls. Mirrors the local
198
+ ``AttachmentStorage``, which copies and expires the same way.
199
+ """
200
+ with self._metadata_lock:
201
+ meta = self._metadata.get(file_id)
202
+ if meta and meta["expires_at"] <= datetime.now():
203
+ del self._metadata[file_id]
204
+ return None
205
+ return dict(meta) if meta else None
206
+
207
+ def get_signed_url(self, file_id: str) -> str:
208
+ """Generate a V4 signed download URL for a previously saved attachment.
209
+
210
+ An entry whose own lifetime has run out is dropped and treated as unknown.
211
+ Metadata is only swept on save, so without this a caller holding a file_id
212
+ could keep minting fresh one-hour URLs for an object long after its first
213
+ URL lapsed — for as long as the bucket's lifecycle rule still keeps it.
214
+ The built-in tools sign immediately and never hand out the id, so this
215
+ guards callers of the storage API rather than the normal response path.
216
+ """
217
+ with self._metadata_lock:
218
+ meta = self._metadata.get(file_id)
219
+ if meta and meta["expires_at"] <= datetime.now():
220
+ del self._metadata[file_id]
221
+ meta = None
222
+ if not meta:
223
+ raise KeyError(f"Unknown attachment file_id: {file_id}")
224
+
225
+ blob = self._get_client().bucket(self.bucket_name).blob(meta["blob_name"])
226
+ expiration = timedelta(seconds=self.expiration_seconds)
227
+
228
+ try:
229
+ # Works when the credentials carry a private key.
230
+ return blob.generate_signed_url(version="v4", expiration=expiration)
231
+ except AttributeError as key_err:
232
+ # Token-only credentials: sign through the IAM signBlob API.
233
+ logger.debug(f"Falling back to IAM-based signing: {key_err}")
234
+ credentials, _ = google.auth.default()
235
+ # Refreshing also resolves a Compute Engine "default" account email.
236
+ credentials.refresh(Request())
237
+ return blob.generate_signed_url(
238
+ version="v4",
239
+ expiration=expiration,
240
+ service_account_email=credentials.service_account_email,
241
+ access_token=credentials.token,
242
+ )
243
+
244
+
245
+ _gcs_attachment_storage: Optional[GCSAttachmentStorage] = None
246
+
247
+
248
+ def get_gcs_attachment_storage() -> GCSAttachmentStorage:
249
+ """Get the global GCS attachment storage instance."""
250
+ global _gcs_attachment_storage
251
+ if _gcs_attachment_storage is None:
252
+ _gcs_attachment_storage = GCSAttachmentStorage()
253
+ return _gcs_attachment_storage
@@ -0,0 +1,339 @@
1
+ """
2
+ SSRF-safe HTTP fetching utilities.
3
+
4
+ Provides async HTTP fetch functions with protection against SSRF attacks,
5
+ DNS rebinding, and redirect-based bypasses. Extracted from gdrive/drive_tools.py
6
+ for reuse across modules (Drive uploads, Gmail URL attachments, etc.).
7
+ """
8
+
9
+ import ipaddress
10
+ import asyncio
11
+ import logging
12
+ import socket
13
+ from contextlib import asynccontextmanager
14
+ from typing import AsyncIterator, Optional
15
+ from urllib.parse import urljoin, urlparse, urlunparse
16
+
17
+ import httpx
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class SSRFFetchError(RuntimeError):
23
+ """Raised when SSRF-safe fetching fails after validation succeeds."""
24
+
25
+
26
+ class PrivateHostError(ValueError):
27
+ """Raised when a URL's host is loopback or a private/internal address."""
28
+
29
+
30
+ def redact_url(url: str) -> str:
31
+ """Return a redacted URL safe for logs and exceptions."""
32
+ parsed_url = urlparse(url)
33
+ if not parsed_url.hostname:
34
+ return "<redacted>"
35
+
36
+ path = parsed_url.path or "/"
37
+ return f"{parsed_url.hostname}{path}"
38
+
39
+
40
+ async def resolve_and_validate_host(hostname: str) -> list[str]:
41
+ """
42
+ Resolve a hostname to IP addresses and validate none are private/internal.
43
+
44
+ Uses getaddrinfo to handle both IPv4 and IPv6. Fails closed on DNS errors.
45
+
46
+ Returns:
47
+ list[str]: Validated resolved IP address strings.
48
+
49
+ Raises:
50
+ ValueError: If hostname resolves to private/internal IPs or DNS fails.
51
+ """
52
+ if not hostname:
53
+ raise ValueError("Invalid URL: no hostname")
54
+
55
+ # Block localhost variants
56
+ if hostname.lower() in ("localhost", "127.0.0.1", "::1", "0.0.0.0"):
57
+ raise PrivateHostError("URLs pointing to localhost are not allowed")
58
+
59
+ # Resolve hostname using getaddrinfo (handles both IPv4 and IPv6)
60
+ try:
61
+ loop = asyncio.get_running_loop()
62
+ addr_infos = await loop.run_in_executor(
63
+ None, socket.getaddrinfo, hostname, None
64
+ )
65
+ except socket.gaierror as e:
66
+ raise ValueError(
67
+ f"Cannot resolve hostname '{hostname}': {e}. "
68
+ "Refusing request (fail-closed)."
69
+ )
70
+
71
+ if not addr_infos:
72
+ raise ValueError(f"No addresses found for hostname: {hostname}")
73
+
74
+ resolved_ips: list[str] = []
75
+ seen_ips: set[str] = set()
76
+ for _family, _type, _proto, _canonname, sockaddr in addr_infos:
77
+ ip_str = sockaddr[0]
78
+ ip = ipaddress.ip_address(ip_str)
79
+ if not ip.is_global:
80
+ raise PrivateHostError(
81
+ f"URLs pointing to private/internal networks are not allowed: "
82
+ f"{hostname} resolves to {ip_str}"
83
+ )
84
+ if ip_str not in seen_ips:
85
+ seen_ips.add(ip_str)
86
+ resolved_ips.append(ip_str)
87
+
88
+ return resolved_ips
89
+
90
+
91
+ async def validate_url_not_internal(url: str) -> list[str]:
92
+ """
93
+ Validate that a URL doesn't point to internal/private networks (SSRF protection).
94
+
95
+ Returns:
96
+ list[str]: Validated resolved IP addresses for the hostname.
97
+
98
+ Raises:
99
+ ValueError: If URL points to localhost or private IP ranges.
100
+ """
101
+ parsed = urlparse(url)
102
+ return await resolve_and_validate_host(parsed.hostname)
103
+
104
+
105
+ def format_host_header(hostname: str, scheme: str, port: Optional[int]) -> str:
106
+ """Format the Host header value for IPv4/IPv6 hostnames."""
107
+ host_value = hostname
108
+ if ":" in host_value and not host_value.startswith("["):
109
+ host_value = f"[{host_value}]"
110
+
111
+ is_default_port = (scheme == "http" and (port is None or port == 80)) or (
112
+ scheme == "https" and (port is None or port == 443)
113
+ )
114
+ if not is_default_port and port is not None:
115
+ host_value = f"{host_value}:{port}"
116
+ return host_value
117
+
118
+
119
+ def build_pinned_url(parsed_url, ip_address_str: str) -> str:
120
+ """Build a URL that targets a resolved IP while preserving path/query."""
121
+ pinned_host = ip_address_str
122
+ if ":" in pinned_host and not pinned_host.startswith("["):
123
+ pinned_host = f"[{pinned_host}]"
124
+
125
+ userinfo = ""
126
+ if parsed_url.username is not None:
127
+ userinfo = parsed_url.username
128
+ if parsed_url.password is not None:
129
+ userinfo += f":{parsed_url.password}"
130
+ userinfo += "@"
131
+
132
+ port_part = f":{parsed_url.port}" if parsed_url.port is not None else ""
133
+ netloc = f"{userinfo}{pinned_host}{port_part}"
134
+
135
+ path = parsed_url.path or "/"
136
+ return urlunparse(
137
+ (
138
+ parsed_url.scheme,
139
+ netloc,
140
+ path,
141
+ parsed_url.params,
142
+ parsed_url.query,
143
+ parsed_url.fragment,
144
+ )
145
+ )
146
+
147
+
148
+ async def fetch_url_with_pinned_ip(
149
+ url: str, *, timeout: Optional[httpx.Timeout] = None
150
+ ) -> httpx.Response:
151
+ """
152
+ Fetch URL content by connecting to a validated, pre-resolved IP address.
153
+
154
+ This prevents DNS rebinding between validation and the outbound connection.
155
+ """
156
+ parsed_url = urlparse(url)
157
+ redacted_url = redact_url(url)
158
+ if parsed_url.scheme not in ("http", "https"):
159
+ raise ValueError(f"Only http:// and https:// are supported: {redacted_url}")
160
+ if not parsed_url.hostname:
161
+ raise ValueError(f"Invalid URL: missing hostname ({redacted_url})")
162
+
163
+ resolved_ips = await validate_url_not_internal(url)
164
+ host_header = format_host_header(
165
+ parsed_url.hostname, parsed_url.scheme, parsed_url.port
166
+ )
167
+
168
+ last_error: Optional[Exception] = None
169
+ for resolved_ip in resolved_ips:
170
+ pinned_url = build_pinned_url(parsed_url, resolved_ip)
171
+ try:
172
+ async with httpx.AsyncClient(
173
+ follow_redirects=False, trust_env=False, timeout=timeout
174
+ ) as client:
175
+ request = client.build_request(
176
+ "GET",
177
+ pinned_url,
178
+ headers={"Host": host_header},
179
+ extensions={"sni_hostname": parsed_url.hostname},
180
+ )
181
+ return await client.send(request)
182
+ except httpx.HTTPError as exc:
183
+ last_error = exc
184
+ logger.warning(
185
+ f"[ssrf_safe_fetch] Failed request via resolved IP {resolved_ip} for host "
186
+ f"{parsed_url.hostname}: {exc.__class__.__name__}"
187
+ )
188
+
189
+ raise SSRFFetchError(
190
+ "Failed to fetch URL after trying "
191
+ f"{len(resolved_ips)} validated IP(s): {redacted_url}"
192
+ ) from last_error
193
+
194
+
195
+ async def ssrf_safe_fetch(
196
+ url: str, *, timeout: Optional[httpx.Timeout] = None
197
+ ) -> httpx.Response:
198
+ """
199
+ Fetch a URL with SSRF protection that covers redirects and DNS rebinding.
200
+
201
+ Validates the initial URL and every redirect target against private/internal
202
+ networks. Disables automatic redirect following and handles redirects manually.
203
+
204
+ Args:
205
+ url: The URL to fetch.
206
+
207
+ Returns:
208
+ httpx.Response with the final response content.
209
+
210
+ Raises:
211
+ ValueError: If any URL in the redirect chain points to a private network.
212
+ SSRFFetchError: If the HTTP request fails.
213
+ """
214
+ max_redirects = 10
215
+ current_url = url
216
+
217
+ for _ in range(max_redirects):
218
+ resp = await fetch_url_with_pinned_ip(current_url, timeout=timeout)
219
+ redacted_current_url = redact_url(current_url)
220
+
221
+ if resp.status_code in (301, 302, 303, 307, 308):
222
+ location = resp.headers.get("location")
223
+ if not location:
224
+ raise SSRFFetchError(
225
+ f"Redirect with no Location header from {redacted_current_url}"
226
+ )
227
+
228
+ # Resolve relative redirects against the current URL
229
+ location = urljoin(current_url, location)
230
+
231
+ redirect_parsed = urlparse(location)
232
+ if redirect_parsed.scheme not in ("http", "https"):
233
+ raise ValueError(
234
+ f"Redirect to disallowed scheme: {redirect_parsed.scheme}"
235
+ )
236
+
237
+ current_url = location
238
+ continue
239
+
240
+ return resp
241
+
242
+ raise SSRFFetchError(
243
+ f"Too many redirects (max {max_redirects}) fetching {redact_url(url)}"
244
+ )
245
+
246
+
247
+ @asynccontextmanager
248
+ async def ssrf_safe_stream(
249
+ url: str,
250
+ *,
251
+ timeout: httpx.Timeout = httpx.Timeout(30.0, connect=5.0),
252
+ ) -> AsyncIterator[httpx.Response]:
253
+ """
254
+ SSRF-safe streaming fetch: validates each redirect target against private
255
+ networks, then streams the final response body without buffering it all
256
+ in memory.
257
+
258
+ Usage::
259
+
260
+ async with ssrf_safe_stream(file_url) as resp:
261
+ async for chunk in resp.aiter_bytes(chunk_size=256 * 1024):
262
+ ...
263
+ """
264
+ max_redirects = 10
265
+ current_url = url
266
+
267
+ # Resolve redirects manually so every hop is SSRF-validated
268
+ for _ in range(max_redirects):
269
+ parsed = urlparse(current_url)
270
+ redacted_url = redact_url(current_url)
271
+ if parsed.scheme not in ("http", "https"):
272
+ raise ValueError(f"Only http:// and https:// are supported: {redacted_url}")
273
+ if not parsed.hostname:
274
+ raise ValueError(f"Invalid URL: missing hostname ({redacted_url})")
275
+
276
+ resolved_ips = await validate_url_not_internal(current_url)
277
+ host_header = format_host_header(parsed.hostname, parsed.scheme, parsed.port)
278
+
279
+ last_error: Optional[Exception] = None
280
+ resp: Optional[httpx.Response] = None
281
+ for resolved_ip in resolved_ips:
282
+ pinned_url = build_pinned_url(parsed, resolved_ip)
283
+ client = httpx.AsyncClient(
284
+ follow_redirects=False, trust_env=False, timeout=timeout
285
+ )
286
+ try:
287
+ request = client.build_request(
288
+ "GET",
289
+ pinned_url,
290
+ headers={"Host": host_header},
291
+ extensions={"sni_hostname": parsed.hostname},
292
+ )
293
+ resp = await client.send(request, stream=True)
294
+ break
295
+ except httpx.HTTPError as exc:
296
+ last_error = exc
297
+ await client.aclose()
298
+ logger.warning(
299
+ f"[ssrf_safe_stream] Failed via IP {resolved_ip} for "
300
+ f"{parsed.hostname}: {exc.__class__.__name__}"
301
+ )
302
+ except Exception:
303
+ await client.aclose()
304
+ raise
305
+
306
+ if resp is None:
307
+ raise SSRFFetchError(
308
+ f"Failed to fetch URL after trying {len(resolved_ips)} validated IP(s): "
309
+ f"{redacted_url}"
310
+ ) from last_error
311
+
312
+ if resp.status_code in (301, 302, 303, 307, 308):
313
+ location = resp.headers.get("location")
314
+ await resp.aclose()
315
+ await client.aclose()
316
+ if not location:
317
+ raise SSRFFetchError(
318
+ f"Redirect with no Location header from {redacted_url}"
319
+ )
320
+ location = urljoin(current_url, location)
321
+ redirect_parsed = urlparse(location)
322
+ if redirect_parsed.scheme not in ("http", "https"):
323
+ raise ValueError(
324
+ f"Redirect to disallowed scheme: {redirect_parsed.scheme}"
325
+ )
326
+ current_url = location
327
+ continue
328
+
329
+ # Non-redirect — yield the streaming response
330
+ try:
331
+ yield resp
332
+ finally:
333
+ await resp.aclose()
334
+ await client.aclose()
335
+ return
336
+
337
+ raise SSRFFetchError(
338
+ f"Too many redirects (max {max_redirects}) fetching {redact_url(url)}"
339
+ )