Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(azure-blob): Pinned resolved IPs (#122153)

Tomás Farías Santana4a01b38a5994
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 29033695d9c3..83f6e42c2798 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -1550,12 +1550,12 @@ class TestAzureBlobIntegration:
],
)
@override_settings(FORCE_URL_VALIDATION=True)
- @patch("posthog.models.integration.azure_blob.is_url_allowed")
+ @patch("dns.resolver.Resolver.resolve_name")
def test_create_azure_blob_integration(
- self, mock_is_url_allowed: MagicMock, connection_string: str, client: HttpClient
+ self, mock_resolve_name: MagicMock, connection_string: str, client: HttpClient
) -> None:
# Required mock otherwise we need a valid hostname for tests
- mock_is_url_allowed.return_value = (True, None)
+ mock_resolve_name.return_value = MagicMock(addresses=MagicMock(return_value=["93.184.216.34"]))
client.force_login(self.user)
response = client.post(
diff --git a/posthog/models/integration/azure_blob.py b/posthog/models/integration/azure_blob.py
index ece811414c86..4b1fc1dc6a01 100644
--- a/posthog/models/integration/azure_blob.py
+++ b/posthog/models/integration/azure_blob.py
@@ -1,7 +1,19 @@
"""Azure Blob Storage integration."""
+import operator
+from functools import reduce
+from itertools import groupby
+from operator import itemgetter
+from urllib.parse import urlsplit
+
from posthog.models.user import User
-from posthog.security.url_validation import _dev_bypass_enabled, _test_bypass_enabled, is_url_allowed
+from posthog.security.url_validation import (
+ ResolvedIPs,
+ _dev_bypass_enabled,
+ _test_bypass_enabled,
+ canonicalize_host,
+ validate_url_and_pin_ips,
+)
from . import model
@@ -89,7 +101,7 @@ class EndpointNotAllowedError(ValueError):
"""Distinct error raised when an endpoint is not allowed."""
-def validate_azure_blob_connection_string(connection_string: str) -> None:
+def validate_azure_blob_connection_string(connection_string: str) -> dict[str, ResolvedIPs] | None:
"""Validate an Azure Blob connection string.
Extract its parts, evaluate all required settings are included, and check
@@ -142,14 +154,26 @@ def validate_azure_blob_connection_string(connection_string: str) -> None:
suffix = settings.get("ENDPOINTSUFFIX") or "core.windows.net"
derived_endpoints.append(f"{protocol}://{account_name}.blob.{suffix}")
+ if not validation_applies:
+ return None
+
+ pinned_ips: list[tuple[str, ResolvedIPs]] = []
for endpoint in explicit_endpoints + derived_endpoints:
- if validation_applies and not endpoint.lower().startswith("https://"):
+ if not endpoint.lower().startswith("https://"):
raise ValueError("Endpoints in the connection string must use https")
- if validation_applies:
- allowed, error = is_url_allowed(endpoint)
- if not allowed:
- raise EndpointNotAllowedError("Invalid endpoint found in connection string")
+ verdict = validate_url_and_pin_ips(endpoint)
+
+ if not verdict.allowed or not verdict.pinned_ips:
+ raise EndpointNotAllowedError("Invalid endpoint found in connection string")
+
+ host = canonicalize_host(urlsplit(endpoint).hostname or "")
+ pinned_ips.append((host, verdict.pinned_ips))
+
+ return {
+ host: reduce(operator.or_, (s[1] for s in grouped), set())
+ for host, grouped in groupby(sorted(pinned_ips, key=itemgetter(0)), key=itemgetter(0))
+ }
def strip_leading_whitespace(conn_str: str) -> str:
diff --git a/posthog/security/pinned_aiohttp.py b/posthog/security/pinned_aiohttp.py
new file mode 100644
index 000000000000..9202dd48f589
--- /dev/null
+++ b/posthog/security/pinned_aiohttp.py
@@ -0,0 +1,111 @@
+import socket
+import ipaddress
+from collections.abc import Callable, Mapping, Sequence
+from contextvars import ContextVar
+from typing import Any, Literal
+
+from django.conf import settings
+
+from aiohttp import ClientRequest, ClientSession, ClientTimeout, TCPConnector
+from aiohttp.abc import AbstractResolver, ResolveResult
+from aiohttp.connector import Connection
+from aiohttp.tracing import Trace
+from yarl import URL
+
+from posthog.security.pinned_requests import SSRFBlockedError
+from posthog.security.url_validation import ResolvedIPs, canonicalize_host
+
+
+def _get_family_from_ip(
+ ip: ipaddress.IPv4Address | ipaddress.IPv6Address,
+) -> Literal[socket.AddressFamily.AF_INET] | Literal[socket.AddressFamily.AF_INET6]:
+ return socket.AF_INET if ip.version == 4 else socket.AF_INET6
+
+
+def _make_filter_ip_family(
+ family: socket.AddressFamily,
+) -> Callable[[ipaddress.IPv4Address | ipaddress.IPv6Address], bool]:
+ def _filter(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ if family not in (socket.AF_UNSPEC, _get_family_from_ip(ip)):
+ return False
+ return True
+
+ return _filter
+
+
+class PinnedResolver(AbstractResolver):
+ """DNS resolver pinned to pre-resolved ips for hosts.
+
+ After IPs are validated, this re-uses the hosts mapped to the validated IPs
+ instead of resolving DNS.
+ """
+
+ def __init__(self, host_to_resolved_ips: Mapping[str, ResolvedIPs]) -> None:
+ self._pinned = host_to_resolved_ips
+
+ async def resolve(
+ self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET
+ ) -> list[ResolveResult]:
+ """Return pinned ips for host, if any.
+
+ Raises:
+ SSRFBlockedError: When there are no pinned ips for the host.
+ """
+ ips = self._pinned.get(canonicalize_host(host))
+ if not ips:
+ raise SSRFBlockedError(f"Unknown host: {host}")
+
+ _filter_ip_family = _make_filter_ip_family(family=family)
+
+ return [
+ ResolveResult(
+ hostname=host,
+ host=str(ip),
+ port=port,
+ family=_get_family_from_ip(ip),
+ proto=socket.IPPROTO_TCP,
+ flags=socket.AI_NUMERICHOST,
+ )
+ for ip in filter(_filter_ip_family, ips)
+ ]
+
+ async def close(self) -> None:
+ pass
+
+
+class PinnedTCPConnector(TCPConnector):
+ def __init__(self, host_to_resolved_ips: Mapping[str, ResolvedIPs], **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self._host_to_resolved_ips = host_to_resolved_ips
+ self._pinned_resolver = PinnedResolver(host_to_resolved_ips)
+ self._trusted_proxies = frozenset(URL(url) for url in settings.SSRF_TRUSTED_PROXY_URLS)
+ self._using_proxy: ContextVar[bool] = ContextVar("pinned_aiohttp_using_proxy", default=False)
+
+ async def connect(self, req: ClientRequest, traces: list[Trace], timeout: ClientTimeout) -> Connection:
+ host = req.url.raw_host
+ assert host is not None
+ if self._host_to_resolved_ips and not self._host_to_resolved_ips.get(canonicalize_host(host)):
+ raise SSRFBlockedError(f"Unknown host: {host}")
+
+ if req.proxy is not None and req.proxy not in self._trusted_proxies:
+ raise SSRFBlockedError(
+ "Outbound proxy is not trusted. Ask an administrator to configure SSRF_TRUSTED_PROXY_URLS."
+ )
+
+ # Proxied requests bypass pins, contextvar keeps things local to this
+ # task so other concurrent connection attempts don't read this.
+ token = self._using_proxy.set(req.proxy is not None)
+ try:
+ return await super().connect(req, traces, timeout)
+ finally:
+ self._using_proxy.reset(token)
+
+ async def _resolve_host(self, host: str, port: int, traces: Sequence[Trace] | None = None) -> list[ResolveResult]:
+ if self._using_proxy.get() or not self._host_to_resolved_ips:
+ return await super()._resolve_host(host, port, traces)
+ return await self._pinned_resolver.resolve(host, port, socket.AddressFamily(self.family))
+
+
+def pinned_session(host_to_resolved_ips: Mapping[str, ResolvedIPs], **kwargs: Any) -> ClientSession:
+ connector = PinnedTCPConnector(host_to_resolved_ips)
+ return ClientSession(connector=connector, trust_env=True, **kwargs)
diff --git a/posthog/security/test/test_pinned_aiohttp.py b/posthog/security/test/test_pinned_aiohttp.py
new file mode 100644
index 000000000000..8ef082262993
--- /dev/null
+++ b/posthog/security/test/test_pinned_aiohttp.py
@@ -0,0 +1,224 @@
+import os
+import ssl
+import socket
+import asyncio
+import ipaddress
+
+import pytest
+from unittest.mock import AsyncMock, Mock, patch
+
+from django.test import override_settings
+
+import aiohttp
+
+from posthog.security.pinned_aiohttp import PinnedResolver, pinned_session
+from posthog.security.pinned_requests import SSRFBlockedError
+from posthog.security.url_validation import ResolvedIPs
+
+PUBLIC_IP = ipaddress.ip_address("93.184.216.34")
+PROXY_URL = "http://proxy.example.com:3128"
+
+
+class ConnectionIntercepted(Exception):
+ pass
+
+
[email protected](autouse=True)
+def clear_proxy_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ for key in list(os.environ):
+ if key.lower().endswith("_proxy"):
+ monkeypatch.delenv(key)
+
+
+ "url,host,address,host_header",
+ [
+ ("https://example.com:8443/path", "example.com", PUBLIC_IP, "example.com:8443"),
+ ("https://éxample.com./path", "xn--xample-9ua.com", PUBLIC_IP, "xn--xample-9ua.com"),
+ ("http://93.184.216.34/path", "93.184.216.34", PUBLIC_IP, "93.184.216.34"),
+ ("https://example.com/path", "example.com", ipaddress.ip_address("2001:4860:4860::8888"), "example.com"),
+ ],
+)
+async def test_direct_connections_keep_pins_and_tls_identity(
+ url: str, host: str, address: ipaddress.IPv4Address | ipaddress.IPv6Address, host_header: str
+) -> None:
+ with (
+ patch("aiohttp.connector.DefaultResolver.resolve", side_effect=AssertionError("Unexpected DNS lookup")),
+ patch("aiohttp.TCPConnector._wrap_create_connection", side_effect=ConnectionIntercepted) as connect,
+ ):
+ async with pinned_session({host: {address}}) as client:
+ with pytest.raises(ConnectionIntercepted):
+ await client.get(url)
+
+ connect.assert_awaited_once()
+ kwargs = connect.call_args.kwargs
+ assert kwargs["addr_infos"][0][4][0] == str(address)
+ request = kwargs["req"]
+ assert request.headers["Host"] == host_header
+ if request.url.scheme == "https":
+ assert kwargs["server_hostname"] == host
+ assert kwargs["ssl"].verify_mode == ssl.CERT_REQUIRED
+ assert kwargs["ssl"].check_hostname
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
[email protected]("pinned", [False, True])
+ "url,environment,explicit_proxy,proxied",
+ [
+ ("https://example.com/", {}, None, False),
+ ("https://example.com/", {"HTTPS_PROXY": PROXY_URL}, None, True),
+ ("http://example.com/", {"HTTP_PROXY": PROXY_URL}, None, True),
+ ("https://example.com/", {"HTTPS_PROXY": PROXY_URL, "NO_PROXY": "example.com"}, None, False),
+ ("https://example.com/", {}, PROXY_URL, True),
+ ],
+)
+async def test_proxy_routing(
+ url: str,
+ environment: dict[str, str],
+ explicit_proxy: str | None,
+ proxied: bool,
+ pinned: bool,
+) -> None:
+ with (
+ patch.dict(os.environ, environment),
+ patch(
+ "aiohttp.connector.DefaultResolver.resolve",
+ return_value=[
+ {
+ "hostname": "proxy.example.com" if proxied else "example.com",
+ "host": "10.0.0.2" if proxied else "127.0.0.1",
+ "port": 3128 if proxied else 443,
+ "family": socket.AF_INET,
+ "proto": socket.IPPROTO_TCP,
+ "flags": socket.AI_NUMERICHOST,
+ }
+ ],
+ ) as resolve,
+ patch("aiohttp.TCPConnector._wrap_create_connection", side_effect=ConnectionIntercepted) as connect,
+ ):
+ async with pinned_session({"example.com": {PUBLIC_IP}} if pinned else {}) as client:
+ with pytest.raises(ConnectionIntercepted):
+ await client.get(url, proxy=explicit_proxy)
+
+ expected_address = "10.0.0.2" if proxied else (str(PUBLIC_IP) if pinned else "127.0.0.1")
+ assert connect.call_args.kwargs["addr_infos"][0][4][0] == expected_address
+ if proxied or not pinned:
+ resolve.assert_awaited_once()
+ assert resolve.call_args.args[0] == ("proxy.example.com" if proxied else "example.com")
+ else:
+ resolve.assert_not_awaited()
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
[email protected]("pinned", [False, True])
[email protected]("proxy", ["http://proxy.example.com:3129", "http://other.example.com:3128"])
+async def test_untrusted_proxy_is_rejected_before_connecting(proxy: str, pinned: bool) -> None:
+ with patch("aiohttp.TCPConnector.connect", side_effect=AssertionError("Unexpected connection")) as connect:
+ async with pinned_session({"example.com": {PUBLIC_IP}} if pinned else {}) as client:
+ with pytest.raises(SSRFBlockedError, match="proxy"):
+ await client.get("https://example.com/", proxy=proxy, headers={"Authorization": "Bearer fake-token"})
+ connect.assert_not_awaited()
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
[email protected]("proxy", [None, PROXY_URL])
+ "target,allowed", [("/continued", True), ("https://other.example.com/", False), ("http://169.254.169.254/", False)]
+)
+async def test_redirects_only_reuse_validated_hosts(proxy: str | None, target: str, allowed: bool) -> None:
+ response = Mock(spec=aiohttp.ClientResponse)
+ response.status = 302
+ response.method = "GET"
+ response.headers = {"Location": target}
+ response._raw_cookie_headers = ()
+ response.start = AsyncMock()
+
+ with (
+ patch("aiohttp.TCPConnector.connect", return_value=Mock()) as connect,
+ patch("aiohttp.ClientRequest.send", side_effect=[response, ConnectionIntercepted]) as send,
+ ):
+ async with pinned_session({"example.com": {PUBLIC_IP}}) as client:
+ with pytest.raises(ConnectionIntercepted if allowed else SSRFBlockedError):
+ await client.get("https://example.com/", proxy=proxy)
+
+ assert connect.await_count == (2 if allowed else 1)
+ assert send.await_count == (2 if allowed else 1)
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
+async def test_proxy_tunnel_keeps_tls_hostname_and_verification() -> None:
+ proxy_response = Mock(spec=aiohttp.ClientResponse)
+ proxy_response.status = 200
+ proxy_response.start = AsyncMock(return_value=proxy_response)
+ transport = Mock(spec=asyncio.Transport)
+ transport.get_extra_info.return_value = None
+
+ with (
+ patch(
+ "aiohttp.connector.DefaultResolver.resolve",
+ return_value=[
+ {
+ "hostname": "proxy.example.com",
+ "host": "10.0.0.2",
+ "port": 3128,
+ "family": socket.AF_INET,
+ "proto": socket.IPPROTO_TCP,
+ "flags": socket.AI_NUMERICHOST,
+ }
+ ],
+ ),
+ patch("aiohttp.TCPConnector._wrap_create_connection", return_value=(transport, Mock())),
+ patch("aiohttp.ClientRequest.send", return_value=proxy_response),
+ patch.object(
+ asyncio.get_running_loop(), "start_tls", side_effect=ssl.SSLCertVerificationError("Rejected certificate")
+ ) as start_tls,
+ ):
+ async with pinned_session({"example.com": {PUBLIC_IP}}) as client:
+ with pytest.raises(aiohttp.ClientConnectorCertificateError):
+ await client.get("https://example.com/", proxy=PROXY_URL)
+
+ start_tls.assert_awaited_once()
+ assert start_tls.call_args.kwargs["server_hostname"] == "example.com"
+ context = start_tls.call_args.args[2]
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
+async def test_proxy_rejection_does_not_fall_back_to_direct() -> None:
+ error = aiohttp.ClientHttpProxyError(Mock(), (), status=403, message="Forbidden")
+ with (
+ patch("aiohttp.TCPConnector._create_proxy_connection", side_effect=error) as proxy_connect,
+ patch(
+ "aiohttp.TCPConnector._create_direct_connection", side_effect=AssertionError("Unexpected fallback")
+ ) as direct,
+ ):
+ async with pinned_session({"example.com": {PUBLIC_IP}}) as client:
+ with pytest.raises(aiohttp.ClientHttpProxyError):
+ await client.get("https://example.com/", proxy=PROXY_URL)
+
+ proxy_connect.assert_awaited_once()
+ direct.assert_not_awaited()
+
+
+@override_settings(SSRF_TRUSTED_PROXY_URLS=[PROXY_URL])
[email protected]("proxy", [None, PROXY_URL])
[email protected]("pins", [{"example.com": set()}, {"other.example.com": {PUBLIC_IP}}])
+async def test_missing_pins_reject_before_connecting(pins: dict[str, ResolvedIPs], proxy: str | None) -> None:
+ with pytest.raises(SSRFBlockedError):
+ await PinnedResolver(pins).resolve("example.com", 443)
+
+ with patch("aiohttp.TCPConnector.connect", side_effect=AssertionError("Unexpected connection")) as connect:
+ async with pinned_session(pins) as client:
+ with pytest.raises(SSRFBlockedError):
+ await client.get("https://example.com/", proxy=proxy)
+
+ connect.assert_not_awaited()
diff --git a/products/batch_exports/backend/destination_tests/azure_blob.py b/products/batch_exports/backend/destination_tests/azure_blob.py
index af00c22b9994..98492b7d76c2 100644
--- a/products/batch_exports/backend/destination_tests/azure_blob.py
+++ b/products/batch_exports/backend/destination_tests/azure_blob.py
@@ -1,6 +1,7 @@
import collections.abc
-from posthog.models.integration.azure_blob import strip_leading_whitespace, validate_azure_blob_connection_string
+from posthog.models.integration.azure_blob import EndpointNotAllowedError, strip_leading_whitespace
+from posthog.security.pinned_requests import SSRFBlockedError
from products.batch_exports.backend.destination_tests.base import (
DestinationTest,
@@ -37,27 +38,24 @@ class AzureBlobContainerTestStep(DestinationTestStep):
async def _run_step(self) -> DestinationTestStepResult:
"""Run this test step."""
from azure.core.exceptions import ClientAuthenticationError, ResourceNotFoundError, ServiceRequestError
- from azure.storage.blob.aio import BlobServiceClient
+
+ from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (
+ MalformedConnectionStringError,
+ azure_container_client,
+ )
assert self.connection_string is not None
assert self.container_name is not None
connection_string = strip_leading_whitespace(self.connection_string)
try:
- validate_azure_blob_connection_string(connection_string)
- except ValueError as e:
+ async with azure_container_client(connection_string, self.container_name) as client:
+ await client.get_container_properties()
+ except (MalformedConnectionStringError, EndpointNotAllowedError, SSRFBlockedError) as e:
return DestinationTestStepResult(
status=Status.FAILED,
message=f"Invalid connection string: {str(e)}",
)
-
- try:
- async with BlobServiceClient.from_connection_string(
- connection_string, permit_redirects=False
- ) as blob_service_client:
- container_client = blob_service_client.get_container_client(self.container_name)
- await container_client.get_container_properties()
-
except ResourceNotFoundError:
return DestinationTestStepResult(
status=Status.FAILED,
@@ -73,11 +71,6 @@ class AzureBlobContainerTestStep(DestinationTestStep):
status=Status.FAILED,
message=f"Could not connect to Azure Blob Storage: {err}",
)
- except ValueError as err:
- return DestinationTestStepResult(
- status=Status.FAILED,
- message=f"Invalid connection string format: {err}",
- )
return DestinationTestStepResult(status=Status.PASSED)
diff --git a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
index 22db2333d3d8..5a553acf27ac 100644
--- a/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
+++ b/products/batch_exports/backend/temporal/destinations/azure_blob_batch_export.py
@@ -2,10 +2,13 @@ import json
import asyncio
import datetime as dt
import dataclasses
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from django.conf import settings
from azure.core.exceptions import HttpResponseError
+from azure.core.pipeline.transport import AioHttpTransport
from azure.storage.blob import StorageErrorCode
from azure.storage.blob.aio import BlobServiceClient, ContainerClient, ExponentialRetry
from structlog.contextvars import bind_contextvars
@@ -14,6 +17,7 @@ from temporalio.common import RetryPolicy
from posthog.models.integration import AzureBlobIntegration, Integration
from posthog.models.integration.azure_blob import EndpointNotAllowedError, validate_azure_blob_connection_string
+from posthog.security.pinned_aiohttp import pinned_session
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_write_only_logger
@@ -52,9 +56,11 @@ NON_RETRYABLE_ERROR_TYPES = (
"AzureBlobIntegrationError",
"AzureBlobIntegrationNotFoundError",
"ClientAuthenticationError",
+ "EndpointNotAllowedError",
"MalformedConnectionStringError",
"MissingRequiredPermissionsError",
"ResourceNotFoundError",
+ "SSRFBlockedError",
"UnsupportedCompressionError",
"UnsupportedFileFormatError",
)
@@ -134,6 +140,44 @@ def azure_blob_default_fields() -> list[BatchExportField]:
return default_fields
+@asynccontextmanager
+async def azure_container_client(connection_string: str, container_name: str) -> AsyncIterator[ContainerClient]:
+ try:
+ pinned_ips = await asyncio.to_thread(validate_azure_blob_connection_string, connection_string)
+ except EndpointNotAllowedError:
+ raise
+ except ValueError:
+ raise MalformedConnectionStringError()
+
+ async with pinned_session(pinned_ips or {}) as session:
+ async with AioHttpTransport(
+ session=session,
+ # Increase the read timeout to 10 minutes to account for large uploads.
+ read_timeout=600,
+ # Preserved default from BlobServiceClient
+ connection_timeout=20,
+ ) as transport:
+ try:
+ blob_service_client = BlobServiceClient.from_connection_string(
+ connection_string,
+ transport=transport,
+ # These are Azure SDK defaults but we set them explicitly for visibility.
+ # See: https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient
+ # Blobs larger than `max_single_put_size` are uploaded in blocks of `max_block_size`.
+ max_single_put_size=64 * 1024 * 1024, # 64 MiB
+ max_block_size=4 * 1024 * 1024, # 4 MiB
+ # Azure SDK defaults but we set them explicitly for visibility.
+ retry_policy=ExponentialRetry(initial_backoff=15, increment_base=3, retry_total=3),
+ permit_redirects=False,
+ )
+ except ValueError:
+ # The SDK does other checks that we don't
+ raise MalformedConnectionStringError()
+
+ async with blob_service_client as client:
+ yield client.get_container_client(container_name)
+
+
class AzureBlobConsumer(Consumer):
"""Consumer that uploads data to Azure Blob Storage."""
@@ -154,6 +198,7 @@ class AzureBlobConsumer(Consumer):
super().__init__(model=model.name)
self.container_client = container_client
+
self.prefix = prefix
self.data_interval_start = data_interval_start
self.data_interval_end = data_interval_end
@@ -169,35 +214,13 @@ class AzureBlobConsumer(Consumer):
self.files_uploaded: list[str] = []
@classmethod
- async def from_inputs(
+ def from_inputs(
cls,
inputs: AzureBlobInsertInputs,
- connection_string: str,
+ /,
+ container_client: ContainerClient,
max_concurrency: int,
) -> "AzureBlobConsumer":
- # Blobs larger than `max_single_put_size` are uploaded in blocks of `max_block_size`.
- # These are Azure SDK defaults but we set them explicitly for visibility.
- # See: https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclient
-
- try:
- await asyncio.to_thread(validate_azure_blob_connection_string, connection_string)
- blob_service_client = BlobServiceClient.from_connection_string(
- conn_str=connection_string,
- max_single_put_size=64 * 1024 * 1024, # 64 MiB
- max_block_size=4 * 1024 * 1024, # 4 MiB
- # Increase the read timeout to 10 minutes to account for large uploads.
- read_timeout=600,
- # Azure SDK defaults but we set them explicitly for visibility.
- retry_policy=ExponentialRetry(initial_backoff=15, increment_base=3, retry_total=3),
- permit_redirects=False,
- )
- except EndpointNotAllowedError:
- raise
- except ValueError:
- raise MalformedConnectionStringError()
-
- container_client = blob_service_client.get_container_client(inputs.container_name)
-
return cls(
container_client=container_client,
prefix=inputs.prefix,
@@ -347,12 +370,6 @@ async def insert_into_azure_blob_activity_from_stage(inputs: AzureBlobInsertInpu
)
return BatchExportResult(records_completed=0, bytes_exported=0)
- consumer = await AzureBlobConsumer.from_inputs(
- inputs=inputs,
- connection_string=azure_integration.connection_string,
- max_concurrency=settings.BATCH_EXPORT_AZURE_BLOB_MAX_CONCURRENT_UPLOADS,
- )
-
json_columns = ("properties", "person_properties", "set", "set_once")
if inputs.file_format.lower() == "jsonlines":
transformer = get_json_stream_transformer(
@@ -367,14 +384,21 @@ async def insert_into_azure_blob_activity_from_stage(inputs: AzureBlobInsertInpu
max_file_size_bytes=inputs.max_file_size_mb * 1024 * 1024 if inputs.max_file_size_mb else 0,
)
- return await run_consumer_from_stage(
- queue=queue,
- consumer=consumer,
- producer_task=producer_task,
- transformer=transformer,
- json_columns=json_columns,
- records_total=inputs.records_total,
- )
+ async with azure_container_client(azure_integration.connection_string, inputs.container_name) as client:
+ consumer = AzureBlobConsumer.from_inputs(
+ inputs,
+ container_client=client,
+ max_concurrency=settings.BATCH_EXPORT_AZURE_BLOB_MAX_CONCURRENT_UPLOADS,
+ )
+
+ return await run_consumer_from_stage(
+ queue=queue,
+ consumer=consumer,
+ producer_task=producer_task,
+ transformer=transformer,
+ json_columns=json_columns,
+ records_total=inputs.records_total,
+ )
@workflow.defn(name="azure-blob-export", failure_exception_types=[workflow.NondeterminismError])
diff --git a/products/batch_exports/backend/tests/destination_tests/test_azure_blob_destination_tests.py b/products/batch_exports/backend/tests/destination_tests/test_azure_blob_destination_tests.py
index f5bf782b6232..f76adb03d91e 100644
--- a/products/batch_exports/backend/tests/destination_tests/test_azure_blob_destination_tests.py
+++ b/products/batch_exports/backend/tests/destination_tests/test_azure_blob_destination_tests.py
@@ -1,11 +1,17 @@
+import os
import uuid
+import socket
import logging
import pytest
+from unittest.mock import AsyncMock, Mock, patch
+
+from django.test import override_settings
from azure.storage.blob.aio import BlobServiceClient
from products.batch_exports.backend.destination_tests.azure_blob import AzureBlobContainerTestStep, Status
+from products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import MalformedConnectionStringError
from products.batch_exports.backend.tests.temporal.destinations.azure_blob.conftest import AZURITE_CONNECTION_STRING
pytestmark = [pytest.mark.asyncio]
@@ -63,8 +69,7 @@ async def test_azure_blob_check_container_invalid_connection_string():
result = await test_step.run()
assert result.status == Status.FAILED
- assert result.message is not None
- assert "Invalid connection string: Malformed connection string" in result.message
+ assert result.message == f"Invalid connection string: {MalformedConnectionStringError()}"
async def test_azure_blob_check_container_emulator_connection_string():
@@ -89,6 +94,74 @@ async def test_azure_blob_check_container_trailing_semicolon_connection_string(c
assert result.status == Status.PASSED
+@override_settings(FORCE_URL_VALIDATION=True, SSRF_TRUSTED_PROXY_URLS=["http://proxy.example.com:3128"])
[email protected]("proxied", [False, True])
+async def test_azure_blob_check_container_uses_validated_ip_without_resolving_again(proxied: bool) -> None:
+ host = "storage.example.com"
+ public_ip = "93.184.216.34"
+ test_step = AzureBlobContainerTestStep(
+ connection_string=f"AccountName=example;AccountKey=ZXhhbXBsZQ==;BlobEndpoint=https://{host}",
+ container_name="test-container",
+ )
+
+ with (
+ patch.dict(
+ os.environ,
+ {
+ **{key: "" for key in os.environ if key.lower().endswith("_proxy")},
+ "HTTPS_PROXY": "http://proxy.example.com:3128" if proxied else "",
+ },
+ ),
+ patch(
+ "dns.resolver.Resolver.resolve_name",
+ side_effect=[
+ Mock(addresses=Mock(return_value=[public_ip])),
+ Mock(addresses=Mock(return_value=["127.0.0.1"])),
+ ],
+ ) as resolve_name,
+ patch(
+ "aiohttp.connector.DefaultResolver.resolve",
+ new_callable=AsyncMock,
+ return_value=[
+ {
+ "hostname": "proxy.example.com",
+ "host": "10.0.0.2",
+ "port": 3128,
+ "family": socket.AF_INET,
+ "proto": socket.IPPROTO_TCP,
+ "flags": socket.AI_NUMERICHOST,
+ }
+ ],
+ ) as resolve_again,
+ patch(
+ "aiohappyeyeballs.start_connection",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("Socket connection intercepted"),
+ ) as connect,
+ ):
+ result = await test_step.run()
+
+ resolve_name.assert_called_once()
+ assert resolve_name.call_args.args[0] == host
+ if proxied:
+ resolve_again.assert_awaited_once()
+ assert resolve_again.call_args.args[0] == "proxy.example.com"
+ else:
+ resolve_again.assert_not_awaited()
+ connect.assert_awaited_once()
+ assert connect.call_args.kwargs["addr_infos"] == [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ socket.IPPROTO_TCP,
+ "",
+ ("10.0.0.2", 3128) if proxied else (public_ip, 443),
+ )
+ ]
+ assert result.status == Status.FAILED
+ assert result.message == "The test step failed with an unknown error: Socket connection intercepted."
+
+
@pytest.mark.parametrize("step", [AzureBlobContainerTestStep()])
async def test_test_steps_fail_if_not_configured(step):
result = await step.run()