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

[BUG] Incorrect ByteBuffer Offset Handling Causes Data Corruption in writeByteBufferToStream

Open himanchalkaushale opened this issue 2 weeks ago • 3 comments

Describe the bug ImplUtils.writeByteBufferToStream(ByteBuffer buffer, OutputStream stream) ignores ByteBuffer.arrayOffset() when writing array-backed ByteBuffer instances.

When a sliced ByteBuffer (e.g. created via buffer.slice(), Netty byte buffer slicing, or sub-buffer windowing where arrayOffset() > 0) is written to an OutputStream, ImplUtils writes bytes starting at index buffer.position() (which is typically 0 relative to the slice) instead of buffer.arrayOffset() + buffer.position().

Because buffer.array() returns the root backing array, this causes silent data corruption: bytes from index 0 of the backing array are written to the OutputStream instead of the sliced buffer's actual contents, without throwing any errors.

This directly affects:

  • BinaryData.writeTo(OutputStream) (via ByteBufferContent and ListByteBufferContent)
  • FluxUtil.writeToOutputStream(Flux<ByteBuffer>, OutputStream) (via OutputStreamWriteSubscriber)
  • HttpLoggingPolicy

Exception or Stack Trace No exception is thrown when the corrupt write stays within the backing array's bounds. The method completes successfully and corrupts the output stream silently.

If a sliced buffer has buffer.position() + buffer.remaining() > buffer.array().length - buffer.arrayOffset(), OutputStream.write throws:

java.lang.IndexOutOfBoundsException
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:345)
    at com.azure.core.implementation.ImplUtils.writeByteBufferToStream(ImplUtils.java:158)
    at com.azure.core.implementation.util.ByteBufferContent.writeTo(ByteBufferContent.java:84)
    at com.azure.core.util.BinaryData.writeTo(BinaryData.java:1449)

To Reproduce Steps to reproduce the behavior:

  1. Create a backing byte array with distinct header and payload bytes.
  2. Create a sliced ByteBuffer representing only the payload portion (yielding arrayOffset() > 0 and position() == 0).
  3. Wrap the slice in BinaryData.fromByteBuffer(slice) (or call ImplUtils.writeByteBufferToStream(slice, out) directly).
  4. Call binaryData.writeTo(out).
  5. Compare the written bytes against the slice contents. The output contains the header bytes from index 0 instead of the payload.

Code Snippet

import com.azure.core.util.BinaryData;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class SlicedBufferRepro {
    public static void main(String[] args) throws IOException {
        // Backing buffer with 4-byte header [1, 2, 3, 4] and 4-byte payload [50, 60, 70, 80]
        byte[] backingArray = new byte[] { 1, 2, 3, 4, 50, 60, 70, 80 };

        // Sliced view representing the payload [50, 60, 70, 80]
        // Here: slice.hasArray() == true, slice.arrayOffset() == 4, slice.position() == 0, slice.remaining() == 4
        ByteBuffer slice = ByteBuffer.wrap(backingArray, 4, 4).slice();

        BinaryData binaryData = BinaryData.fromByteBuffer(slice);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        binaryData.writeTo(out);

        byte[] result = out.toByteArray();
        System.out.println("Expected: " + Arrays.toString(new byte[] { 50, 60, 70, 80 }));
        System.out.println("Actual:   " + Arrays.toString(result));

        // Actual output: [1, 2, 3, 4] (SILENT DATA CORRUPTION)
        assert Arrays.equals(result, new byte[] { 50, 60, 70, 80 }) : "Data was corrupted!";
    }
}

Expected behavior ImplUtils.writeByteBufferToStream should respect the java.nio.ByteBuffer contract:

"If this buffer is backed by an array then buffer position p corresponds to array index p + arrayOffset()."

The bytes written to the OutputStream should match the exact window represented by the ByteBuffer ([50, 60, 70, 80]), regardless of whether the buffer is sliced or has a non-zero arrayOffset().

Screenshots N/A

Setup (please complete the following information):

  • OS: Windows / Linux / macOS
  • IDE: IntelliJ IDEA / VS Code
  • Library/Libraries: com.azure:azure-core:1.62.0-beta.1 (and all GA 1.x releases since 1.25.0)
  • Java version: 8, 11, 17, 21
  • App Server/Environment: Any (standard JVM)
  • Frameworks: Any

Additional context

Exact Location of the Bug

sdk/core/azure-core/src/main/java/com/azure/core/implementation/ImplUtils.java:153-165:

public static void writeByteBufferToStream(ByteBuffer buffer, OutputStream stream) throws IOException {
    if (buffer.hasArray()) {
        // BUG: buffer.arrayOffset() is missing!
        stream.write(buffer.array(), buffer.position(), buffer.remaining());

        buffer.position(buffer.position() + buffer.remaining());
        return;
    }
    ...
}

Proposed Fix

Update line 158 to add buffer.arrayOffset():

if (buffer.hasArray()) {
    stream.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
    buffer.position(buffer.position() + buffer.remaining());
    return;
}

For non-sliced buffers, buffer.arrayOffset() returns 0, so this change is 100% backwards-compatible and introduces zero regressions while fixing silent corruption for all sliced views.

Information Checklist Kindly make sure that you have added all the following information above and checkoff the required fields otherwise we will treat the issuer as an incomplete report

  • [x] Bug Description Added
  • [x] Repro Steps Added
  • [x] Setup information Added

himanchalkaushale avatar Nov 15 '26 07:11 himanchalkaushale

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

Generated by Agentic Triage for #51267 · auto · 20.5 AIC · ⊞ 16.5K · ◷

github-actions[bot] avatar Nov 15 '26 07:11 github-actions[bot]

🎯 Agentic Issue Triage

Summary: ImplUtils.writeByteBufferToStream ignores ByteBuffer.arrayOffset() for array-backed buffers, so sliced buffers write the wrong bytes (silent corruption or IndexOutOfBoundsException).

📋 Issue Details

Package: com.azure:azure-core (1.62.0-beta.1 and earlier GA 1.x) Affected API: ImplUtils.writeByteBufferToStream, and through it BinaryData.writeTo(OutputStream), FluxUtil.writeToOutputStream, HttpLoggingPolicy Scenarios:

  • Writing BinaryData.fromByteBuffer(slice) where slice.arrayOffset() > 0
  • Writing Flux(ByteBuffer) of sliced buffers to an OutputStream

Root ask: Use buffer.arrayOffset() + buffer.position() as the write offset.

🔎 Debugging / Reproduction Notes

The reporter's repro and proposed one-line fix are consistent with the ByteBuffer contract.

Suggested investigation steps:

  1. Confirm the missing arrayOffset() in ImplUtils.java and check other buffer.array() usages for the same issue.
  2. Add a unit test with a sliced buffer (arrayOffset() > 0) for BinaryData.writeTo and FluxUtil.writeToOutputStream.
  3. Apply the fix and add a CHANGELOG entry.
🏷️ Label Confidence
  • Category: Client — SDK code defect.
  • Service: Azure.Core — the code is in sdk/core/azure-core.
  • Confidence: High — a single unambiguous package.
👥 Owner Routing
  • Matched CODEOWNERS entry: # ServiceLabel: %Azure.Core (line 56) — all of its labels are present.
  • AzureSdkOwners: @alzimmermsft
  • ServiceOwners: none listed
  • Routing action: assigned the AzureSdkOwner and added needs-team-attention because the author is external.
  • Scan notes: %Azure.Core.V2 and %Azure.Core.AMQP do not match because those labels are not predicted.

Generated by Agentic Triage for #51267 · auto · 20.5 AIC · ⊞ 16.5K · ◷

github-actions[bot] avatar Nov 15 '26 07:11 github-actions[bot]

Hi @alzimmermsft, I'd like to work on this issue. Would you be open to assigning it to me? I'm happy to investigate and submit a fix. Thanks!

himanchalkaushale avatar Nov 15 '26 07:11 himanchalkaushale