azure-sdk-for-python icon indicating copy to clipboard operation
azure-sdk-for-python copied to clipboard

Non-ASCII str body gets Content-Length in characters, aiohttp truncates it

Open digit50 opened this issue 1 month ago • 6 comments

  • Package Name: azure-core
  • Package Version: 1.41.0
  • Operating System: Linux (Pop!_OS 24.04)
  • Python Version: 3.12.3

Describe the bug HttpRequest(..., content=<str>) sets Content-Length to the number of characters in the string, not the number of UTF-8 bytes that go on the wire. For any non-ASCII text the header is too small. RequestsTransport hides this because requests recomputes the length, but AioHttpTransport, the default async transport, sends the header as given and only that many bytes of the body, so the service silently receives a truncated body and nothing raises. The legacy HttpRequest.set_text_body has the same problem.

To Reproduce

from azure.core.pipeline.transport import HttpRequest as LegacyHttpRequest
from azure.core.rest import HttpRequest

text = "héllo€"
encoded = text.encode("utf-8")

request = HttpRequest("POST", "https://example.invalid/upload", content=text)
print(f"azure.core.rest.HttpRequest: Content-Length = {request.headers['Content-Length']}, expected {len(encoded)}")

legacy = LegacyHttpRequest("POST", "https://example.invalid/upload")
legacy.set_text_body(text)
print(f"pipeline.transport.HttpRequest.set_text_body: Content-Length = {legacy.headers['Content-Length']}, expected {len(encoded)}")

print(f"UTF-8 body bytes: {encoded!r}")
print(f"first {request.headers['Content-Length']} bytes, what a transport that trusts the header sends: "
      f"{encoded[: int(request.headers['Content-Length'])]!r}")

Output:

azure.core.rest.HttpRequest: Content-Length = 6, expected 9
pipeline.transport.HttpRequest.set_text_body: Content-Length = 6, expected 9
UTF-8 body bytes: b'h\xc3\xa9llo\xe2\x82\xac'
first 6 bytes, what a transport that trusts the header sends: b'h\xc3\xa9llo'

Sending the same request to a local HTTP server, RequestsTransport delivered Content-Length: 9 and all 9 bytes. AioHttpTransport put Content-Length: 6 on the wire followed by exactly b'h\xc3\xa9llo', that is héllo and the first byte of the euro sign, and returned the server's 200 without error.

Expected behavior Content-Length is 9, the length of the UTF-8 encoded body, and every transport sends the full body.

Screenshots N/A

Additional context Cause, at main (c00962557a): set_content_body in sdk/core/azure-core/azure/core/rest/_helpers.py lines 138-145 sets headers["Content-Length"] = str(len(body)) at line 144 while body is still the str. HttpRequest.set_text_body in sdk/core/azure-core/azure/core/pipeline/transport/_base.py line 297 does the same with len(self.data). JSON bodies are not affected because json.dumps escapes non-ASCII by default, and XML bodies are already bytes. The request header tests in tests/test_rest_http_request.py use only ASCII strings, so they pass either way. azure-cosmos fixed the same arithmetic in its own request path in #47008.

Proposed fix: for str content, encode once to UTF-8 and compute the length from the bytes (or store the bytes as the body), and do the same in set_text_body. Add a non-ASCII case to the request header tests and an aiohttp round-trip test.

I'm happy to open a PR with the fix.

digit50 avatar Oct 17 '26 19:10 digit50

Thank you for your feedback. Tagging and routing to the team member(s) best able to assist.

Generated by Agentic Triage for #49588 · copilot · sonnet50 · 24.2 AIC · ⌖ 6.13 AIC · ⊞ 13K · ◷

github-actions[bot] avatar Oct 17 '26 19:10 github-actions[bot]

🎯 Agentic Issue Triage

Summary: For str request bodies containing non-ASCII characters, Content-Length is computed from len(str) (character count) instead of the UTF-8 encoded byte length, causing AioHttpTransport to silently truncate the request body.

📋 Issue Details

Package: azure-core 1.41.0 Affected API: azure.core.rest.HttpRequest (_helpers.set_content_body) and azure.core.pipeline.transport.HttpRequest.set_text_body Scenarios:

  • A str body containing non-ASCII characters (e.g. "héllo€") is passed to HttpRequest(..., content=...) or set_text_body.
  • Content-Length header is set to len(body) (character count) rather than the UTF-8 byte length, so it undercounts multi-byte characters.
  • RequestsTransport masks the bug because requests recomputes Content-Length itself.
  • AioHttpTransport (the default async transport) trusts the given header and sends only that many bytes, truncating the body with no error raised.

Root ask: Fix Content-Length computation to use UTF-8 encoded byte length for str content in both azure.core.rest._helpers.set_content_body and the legacy HttpRequest.set_text_body, and add non-ASCII test coverage (including an aiohttp round-trip test). Author has offered to open a PR.

🔎 Debugging / Reproduction Notes

Issue includes a clear, minimal, self-contained repro script and points to the exact root cause locations:

  • sdk/core/azure-core/azure/core/rest/_helpers.py (set_content_body, ~lines 138-145): headers["Content-Length"] = str(len(body)) computed while body is still a str.
  • sdk/core/azure-core/azure/core/pipeline/transport/_base.py (set_text_body, ~line 297): same len(self.data) arithmetic bug.
  • JSON bodies unaffected (ascii-escaped by json.dumps); XML bodies unaffected (already bytes).
  • Existing tests in tests/test_rest_http_request.py only use ASCII strings, masking the bug.
  • References a prior fix of the same class of bug in azure-cosmos (#47008), suggesting this is a known pattern.

Suggested investigation steps:

  1. Verify set_content_body and set_text_body encode str content to UTF-8 bytes before computing Content-Length (or store the encoded bytes as the body).
  2. Add non-ASCII request header test cases to tests/test_rest_http_request.py.
  3. Add an aiohttp transport round-trip test confirming the full UTF-8 byte body is sent and received intact.
🏷️ Label Confidence
  • Category: Client — azure-core is a data-plane/runtime library, not azure-mgmt-*.
  • Service: Azure.Core — Issue explicitly concerns azure-core's HttpRequest and transport layer.
  • Confidence: High — package and affected code paths are explicitly named, no ambiguity between services, and the label pairing matches quality reference issues (#47186, #39163, #12137) using Client + Azure.Core with customer-reported.
👥 Owner Routing
  • Matched CODEOWNERS entry: # ServiceLabel: %Azure.Core (line 19) — matched the predicted service label during bottom-to-top scan.
  • AzureSdkOwners: @kashifkhan
  • ServiceOwners: none listed
  • Routing action: Assigned @kashifkhan and added needs-team-attention (customer-reported issue with AzureSdkOwner match).
  • Scan notes: The scan also passed # ServiceLabel: %Core.Http (line 16, AzureSdkOwner @kashifkhan) before reaching the matching %Azure.Core entry, but Core.Http did not match the predicted service label Azure.Core.

Generated by Agentic Triage for #49588 · copilot · sonnet50 · 24.2 AIC · ⌖ 6.13 AIC · ⊞ 13K · ◷

github-actions[bot] avatar Oct 17 '26 19:10 github-actions[bot]

Hi @digit50, thank you for the issue and PR. Can you point to an example when this happened while using an SDK scenario please?

kashifkhan avatar Oct 19 '26 19:10 kashifkhan

Hi @digit50. Thank you for opening this issue and giving us the opportunity to assist. To help our team better understand your issue and the details of your scenario please provide a response to the question asked above or the information requested above. This will help us more accurately address your issue.

github-actions[bot] avatar Oct 19 '26 19:10 github-actions[bot]

Hi @digit50, we're sending this friendly reminder because we haven't heard back from you in 7 days. We need more information about this issue to help address it. Please be sure to give us your input. If we don't hear back from you within 14 days of this comment the issue will be automatically closed. Thank you!

github-actions[bot] avatar Oct 26 '26 21:10 github-actions[bot]

Hi @kashifkhan, thanks for looking. Same answer as on #49587: no production incident, I found it reading the azure-core request helpers and reproduced it with the script in the issue against a local aiohttp server.

The scenario is any async client on azure-core that sends a str body containing non-ASCII text (for example a user-supplied name or description in a JSON string built by the caller). Content-Length is computed from the character count before encoding, requests corrects it for the sync transport, but AioHttpTransport trusts the header and the body arrives truncated with no error. The PR (#49591) computes the length from the UTF-8 bytes in both set_content_body and the legacy set_text_body, with tests.

digit50 avatar Oct 27 '26 07:10 digit50