: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(batch-exports): Strip leading whitespace from Azure connection str (#62869)
Tomás Farías Santana6311de3f70ba
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 c7d5d669e004..976329850dd7 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@@ -48,6 +48,7 @@ NON_RETRYABLE_ERROR_TYPES = ("AzureBlobIntegrationError","AzureBlobIntegrationNotFoundError","ClientAuthenticationError",+ "MalformedConnectionStringError","MissingRequiredPermissionsError","ResourceNotFoundError","UnsupportedCompressionError",@@ -95,6 +96,15 @@ class MissingRequiredPermissionsError(Exception):super().__init__("Missing required permissions to run this batch export")+class MalformedConnectionStringError(Exception):+ """Raised when Azure SDK cannot parse a connection string."""++ 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"+ )++def _is_authorization_failure_response_error(err: HttpResponseError) -> bool:"""Check if the provided response error is an authorization failure.@@ -103,6 +113,17 @@ 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@@ -170,15 +191,20 @@ class AzureBlobConsumer(Consumer):# 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- 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),- )++ try:+ blob_service_client = BlobServiceClient.from_connection_string(+ conn_str=_strip_leading_whitespace(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),+ )+ except ValueError:+ raise MalformedConnectionStringError()+container_client = blob_service_client.get_container_client(inputs.container_name)return cls(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 6afb7a81c806..6949c6b0e1ad 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,12 +3,28 @@ 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",[