: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(azure-blob): Validate connection string (#97435)
Tomás Farías Santanaf2312250ea5f
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex eb60748f272d..d388cee93c50 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -1220,6 +1220,75 @@ class TestSnowflakeIntegration:assert expected_error_message in response.json()["detail"]+class TestAzureBlobIntegration:+ @pytest.fixture(autouse=True)+ def setup_integration(self, db):+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create_and_join(+ self.organization, "[email protected]", "test", level=OrganizationMembership.Level.ADMIN+ )++ @pytest.mark.parametrize(+ "connection_string",+ [+ "DefaultEndpointsProtocol=https;AccountName=my-storage-account;AccountKey=my-key;EndpointSuffix=core.windows.net",+ "DefaultEndpointsProtocol=https;AccountName=my-storage-account;AccountKey=my-key;EndpointSuffix=core.usgovcloudapi.net",+ "AccountName=my-storage-account;AccountKey=my-key",+ "AccountName=my-storage-account;AccountKey=YQ==; BlobEndpoint=https://example.com;EndpointSuffix=169.254.169.254",+ ],+ )+ @override_settings(FORCE_URL_VALIDATION=True)+ @patch("posthog.models.integration.azure_blob.is_url_allowed")+ def test_create_azure_blob_integration(+ self, mock_is_url_allowed: 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)+ client.force_login(self.user)++ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "azure-blob",+ "config": {"connection_string": connection_string},+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ integration = Integration.objects.get(id=response.json()["id"])+ assert integration.integration_id == "my-storage-account"++ @pytest.mark.parametrize(+ "connection_string",+ [+ "UseDevelopmentStorage=true;AccountName=devstoreaccount1",+ "AccountName=my-storage-account;AccountKey=my-key;BlobEndpoint=http://169.254.169.254/",+ # Attacker-controlled DefaultEndpointsProtocol is interpolated raw into the derived+ # endpoint by the SDK, so the derived URL must be validated, not assumed https.+ "DefaultEndpointsProtocol=http://169.254.169.254/latest/meta-data?x=;AccountName=a;AccountKey=YQ==;EndpointSuffix=core.windows.net",+ "DefaultEndpointsProtocol=http;AccountName=a;AccountKey=YQ==",+ "AccountName=a;AccountKey=YQ==;BlobEndpoint=http://example.com",+ ],+ )+ @override_settings(FORCE_URL_VALIDATION=True)+ def test_create_azure_blob_integration_rejects_internal_endpoints(self, connection_string, client: HttpClient):+ client.force_login(self.user)++ response = client.post(+ f"/api/environments/{self.team.pk}/integrations",+ {+ "kind": "azure-blob",+ "config": {"connection_string": connection_string},+ },+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not Integration.objects.filter(team=self.team, kind="azure-blob").exists()++class TestIntegrationAPIKeyAccess:@pytest.fixture(autouse=True)def setup_integration(self, db):diff --git a/posthog/models/integration/azure_blob.py b/posthog/models/integration/azure_blob.pyindex 7342ff76b6d8..ece811414c86 100644--- a/posthog/models/integration/azure_blob.py+++ b/posthog/models/integration/azure_blob.py@@ -1,6 +1,7 @@"""Azure Blob Storage integration."""from posthog.models.user import User+from posthog.security.url_validation import _dev_bypass_enabled, _test_bypass_enabled, is_url_allowedfrom . import model@@ -47,6 +48,13 @@ class AzureBlobIntegration:)config: dict[str, str] = {}++ connection_string = strip_leading_whitespace(connection_string)+ try:+ validate_azure_blob_connection_string(connection_string)+ except ValueError as e:+ raise AzureBlobIntegrationError(str(e))+sensitive_config = {"connection_string": connection_string,}@@ -75,3 +83,81 @@ class AzureBlobIntegration:if part.startswith("AccountName="):return part.split("=", 1)[1]return None+++class EndpointNotAllowedError(ValueError):+ """Distinct error raised when an endpoint is not allowed."""+++def validate_azure_blob_connection_string(connection_string: str) -> None:+ """Validate an Azure Blob connection string.++ Extract its parts, evaluate all required settings are included, and check+ that values are supported.+ """+ # Parse exactly as the SDK's parse_connection_str does: no stripping, keys uppercased,+ # later duplicates win. Stricter than the SDK on whitespace-padded keys, which the SDK+ # would silently ignore — a validation/SDK key mismatch is an SSRF bypass.+ settings: dict[str, str] = {}+ for part in connection_string.rstrip(";").split(";"):+ try:+ key, value = part.split("=", maxsplit=1)+ except ValueError:+ raise ValueError("Malformed connection string")+ if key != key.strip():+ raise ValueError("Malformed connection string")+ settings[key.upper()] = value++ if settings.get("USEDEVELOPMENTSTORAGE", "").lower() == "true":+ raise ValueError("Emulator account not supported")++ # HTTPS is required so TLS certificate verification at connect time closes the DNS+ # rebinding window between validation and the SDK's own resolution. Local emulators+ # (Azurite) use HTTP, so the requirement lifts with the dev bypass.+ validation_applies = not (_dev_bypass_enabled() or _test_bypass_enabled())+ protocol = settings.get("DEFAULTENDPOINTSPROTOCOL", "https").lower()+ if protocol not in ("http", "https"):+ raise ValueError("'DefaultEndpointsProtocol' must be 'http' or 'https'")+ if validation_applies and protocol != "https":+ raise ValueError("'DefaultEndpointsProtocol' must be 'https'")++ account_name = settings.get("ACCOUNTNAME")+ if not account_name:+ raise ValueError(+ "Could not extract AccountName from connection string. "+ "Ensure it contains 'AccountName=<your-account-name>;'"+ )++ explicit_endpoints: list[str] = []+ derived_endpoints: list[str] = []++ # For azure blob, we only care about BlobEndpoint.+ # But the docs also mention all these other ones, so we check all of+ # them if present.+ for key in ("BLOBENDPOINT", "FILEENDPOINT", "TABLEENDPOINT", "QUEUEENDPOINT"):+ if key in settings:+ explicit_endpoints.append(settings[key])++ if "BLOBENDPOINT" not in settings:+ suffix = settings.get("ENDPOINTSUFFIX") or "core.windows.net"+ derived_endpoints.append(f"{protocol}://{account_name}.blob.{suffix}")++ for endpoint in explicit_endpoints + derived_endpoints:+ if validation_applies and 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")+++def strip_leading_whitespace(conn_str: str) -> str:+ """Remove any leading whitespace from key=value pairs.++ This is rejected by Azure SDK when parsing. In contrast, I like to help our users+ get things right. I do not strip trailing whitespace as I cannot confirm whether+ values can have trailing whitespace, in contrast to keys, which most definitely+ don't.+ """+ return ";".join(value.lstrip() for value in conn_str.split(";"))diff --git a/posthog/models/test/integration/test_azure_blob.py b/posthog/models/test/integration/test_azure_blob.pynew file mode 100644index 000000000000..e7710a3b0e25--- /dev/null+++ b/posthog/models/test/integration/test_azure_blob.py@@ -0,0 +1,18 @@+import pytest++from posthog.models.integration.azure_blob import strip_leading_whitespace+++ "conn_str,expected",+ [+ # No changes without leading whitespace+ ("AccountName=name;AccountKey=key;SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),+ # Stripped leading whitespace one time+ ("AccountName=name; AccountKey=key;SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),+ # Stripped leading whitespace two times+ ("AccountName=name; AccountKey=key; SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),+ ],+)+def test_strip_leading_whitespace(conn_str: str, expected: str) -> None:+ assert strip_leading_whitespace(conn_str) == expecteddiff --git a/products/batch_exports/backend/api/destination_tests/azure_blob.py b/products/batch_exports/backend/api/destination_tests/azure_blob.pyindex c1118c11149c..e19c3307609b 100644--- a/products/batch_exports/backend/api/destination_tests/azure_blob.py+++ b/products/batch_exports/backend/api/destination_tests/azure_blob.py@@ -1,5 +1,7 @@import collections.abc+from posthog.models.integration.azure_blob import strip_leading_whitespace, validate_azure_blob_connection_string+from products.batch_exports.backend.api.destination_tests.base import (DestinationTest,DestinationTestStep,@@ -40,8 +42,19 @@ class AzureBlobContainerTestStep(DestinationTestStep):assert self.connection_string is not Noneassert 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:+ return DestinationTestStepResult(+ status=Status.FAILED,+ message=f"Invalid connection string: {str(e)}",+ )+try:- async with BlobServiceClient.from_connection_string(self.connection_string) as blob_service_client:+ 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()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.pyindex 36edd7762e48..a74a0c0c43a9 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@@ -1,4 +1,5 @@import json+import asyncioimport datetime as dtimport dataclasses@@ -12,6 +13,7 @@ from temporalio import activity, exceptions, workflowfrom temporalio.common import RetryPolicyfrom posthog.models.integration import AzureBlobIntegration, Integration+from posthog.models.integration.azure_blob import EndpointNotAllowedError, validate_azure_blob_connection_stringfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_write_only_logger@@ -101,7 +103,7 @@ class MalformedConnectionStringError(Exception):def __init__(self):super().__init__(- "The provided connection string was rejected by Azure. Ensure the connection string is made up of key=value pairs separated only by a semicolon (;) with no additional characters in between. Example: AccountName=name;AccountKey=key;SomeKey=somevalue"+ "The provided connection string is malformed or invalid. Ensure the connection string is made up of key=value pairs separated only by a semicolon (;) with no additional characters in between. Additionally, ensure any endpoints point to valid URLs you control. Example: AccountName=name;AccountKey=key;SomeKey=somevalue")@@ -113,17 +115,6 @@ def _is_authorization_failure_response_error(err: HttpResponseError) -> bool:return getattr(err, "error_code", None) == StorageErrorCode.AUTHORIZATION_FAILURE-def _strip_leading_whitespace(conn_str: str) -> str:- """Remove any leading whitespace from key=value pairs.-- This is rejected by Azure SDK when parsing. In contrast, I like to help our users- get things right. I do not strip trailing whitespace as I cannot confirm whether- values can have trailing whitespace, in contrast to keys, which most definitely- don't.- """- return ";".join(value.lstrip() for value in conn_str.split(";"))--@dataclasses.dataclass(kw_only=True)class AzureBlobInsertInputs(BatchExportInsertInputs):container_name: str@@ -193,15 +184,19 @@ class AzureBlobConsumer(Consumer):# See: https://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobserviceclienttry:+ await asyncio.to_thread(validate_azure_blob_connection_string, connection_string)blob_service_client = BlobServiceClient.from_connection_string(- conn_str=_strip_leading_whitespace(connection_string),+ conn_str=connection_string,max_single_put_size=64 * 1024 * 1024, # 64 MiBmax_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:+ raiseexcept ValueError:raise MalformedConnectionStringError()diff --git a/products/batch_exports/backend/tests/api/destination_tests/test_azure_blob_destination_tests.py b/products/batch_exports/backend/tests/api/destination_tests/test_azure_blob_destination_tests.pyindex 3e2a8a3cad5c..6e6d0943d152 100644--- a/products/batch_exports/backend/tests/api/destination_tests/test_azure_blob_destination_tests.py+++ b/products/batch_exports/backend/tests/api/destination_tests/test_azure_blob_destination_tests.py@@ -64,7 +64,29 @@ async def test_azure_blob_check_container_invalid_connection_string():assert result.status == Status.FAILEDassert result.message is not None- assert "Invalid connection string format" in result.message+ assert "Invalid connection string: Malformed connection string" in result.message+++async def test_azure_blob_check_container_emulator_connection_string():+ test_step = AzureBlobContainerTestStep(+ connection_string="UseDevelopmentStorage=true;AccountName=devstoreaccount1",+ container_name="test-container",+ )+ result = await test_step.run()++ assert result.status == Status.FAILED+ assert result.message is not None+ assert "Invalid connection string" in result.message+++async def test_azure_blob_check_container_trailing_semicolon_connection_string(container_name, azurite_container):+ test_step = AzureBlobContainerTestStep(+ connection_string=AZURITE_CONNECTION_STRING + ";",+ container_name=container_name,+ )+ result = await test_step.run()++ assert result.status == Status.PASSED@pytest.mark.parametrize("step", [AzureBlobContainerTestStep()])diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_utils.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_utils.pyindex 6949c6b0e1ad..6afb7a81c806 100644--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_utils.py+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_utils.py@@ -3,28 +3,12 @@ import pytestfrom products.batch_exports.backend.temporal.destinations.azure_blob_batch_export import (COMPRESSION_EXTENSIONS,FILE_FORMAT_EXTENSIONS,- _strip_leading_whitespace,)from products.batch_exports.backend.temporal.destinations.utils import get_key_prefix, get_manifest_key, get_object_keypytestmark = [pytest.mark.asyncio, pytest.mark.django_db]- "conn_str,expected",- [- # No changes without leading whitespace- ("AccountName=name;AccountKey=key;SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),- # Stripped leading whitespace one time- ("AccountName=name; AccountKey=key;SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),- # Stripped leading whitespace two times- ("AccountName=name; AccountKey=key; SomeKey=value", "AccountName=name;AccountKey=key;SomeKey=value"),- ],-)-def test_strip_leading_whitespace(conn_str: str, expected: str) -> None:- assert _strip_leading_whitespace(conn_str) == expected--@pytest.mark.parametrize("file_format,compression,expected_filename",[