Skip to content

fix: encode the bytes of typed array data in data_base64 - #682

Open
rida-ghreizy wants to merge 1 commit into
cloudevents:mainfrom
rida-ghreizy:fix/typed-array-base64
Open

rida-ghreizy wants to merge 1 commit into
cloudevents:mainfrom
rida-ghreizy:fix/typed-array-base64

Conversation

@rida-ghreizy

Copy link
Copy Markdown

Proposed Changes

When an event's data is a typed array, the CloudEvent constructor sets data_base64 = asBase64(data). asBuffer (src/event/validation.ts) converted the array with Buffer.from(typedArray). That copies the element values, one byte per element, not the array's bytes. Anything wider than 8 bits was corrupted, and structured messages (HTTP, Kafka, MQTT) carry that data_base64:

data Bytes in data_base64 before After (the array's real bytes)
new Uint8Array([1, 2, 255]) 1,2,255 1,2,255
new Uint16Array([256, 1]) 0,1 0,1,1,0
new Float32Array([1.5]) 1 0,0,192,63
Uint16Array view over part of a larger buffer element values only the viewed bytes

This PR copies the underlying bytes with Buffer.from(view.buffer, view.byteOffset, view.byteLength). Buffers are returned as before, and 8-bit arrays produce the same output as before.

Description

The existing tests in test/integration/spec_1_tests.ts compare data_base64 with asBase64(...) of the same data, so they pass whatever asBase64 does. I added, for every typed array type, a test that compares data_base64 with the base64 of the array's actual bytes, plus a test for a view over part of a larger buffer.

Without the change, 7 of the new tests fail: the 16-, 32- and 64-bit types and the view. With it, the full suite passes (npx mocha --exit --require ts-node/register ./test/integration/**/*.ts: 244 passing), and ESLint is clean on the changed files.

asBuffer used Buffer.from(typedArray), which copies the element values
truncated to one byte each, so Uint16Array, Int32Array, Float32Array
and other wide arrays were corrupted in data_base64. Copy the underlying
bytes of the view instead, and test every typed array type against its
real bytes.

Signed-off-by: rida <ghreizyrida1@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant