kotlinx-io icon indicating copy to clipboard operation
kotlinx-io copied to clipboard

Construct a ByteArrayInputStream from a ByteString without copying bytes or using UnsafeByteStringOperations

Open mgroth0 opened this issue 1 year ago • 2 comments
trafficstars

Creating a ByteArrayInputStream from a ByteString gives us an InputStream, which is used in many contexts in java. My understanding is that it is completely safe, since a ByteArrayInputStream only reads the underlying ByteArray and does not write to it.

Currently, I believe there are only two ways to get a ByteArrayInputStream from a ByteString:

  1. Use UnsafeByteStringOperations
  2. Copy the bytes

I am wondering if the library could provide a method to get an InputStream (it doesn't necessarily have to be a ByteArrayInputStream, but why not) that is declared safe and doesn't copy bytes.

mgroth0 avatar Apr 05 '24 08:04 mgroth0

It was not considered previously, but in the same way Java stdlib provides StringReader for String, we can also provide an InputStream-view over ByteString.

My understanding is that it is completely safe, since a ByteArrayInputStream only reads the underlying ByteArray and does not write to it.

It depends: ByteArrayInputStream itself is safe, but its transferTo method exposes internal byte array to an OutputStream which, if implemented maliciously, can mutate array's content.

fzhinkin avatar Apr 05 '24 09:04 fzhinkin

ByteArrayInputStream itself is safe, but its transferTo method exposes internal byte array

Thanks for pointing that out. I was unsure if there might be some vulnerability like that.

Maybe this library can implement a custom InputStream which wraps around ByteArrayInputStream, but more more strictly preventing the ByteArray from leaking out?

I guess this might mean making transferTo much less efficient, either by copying bytes or by transfering them one at a time. I am curious what is the best solution here.

mgroth0 avatar Apr 05 '24 09:04 mgroth0