grafana / xk6-webcrypto

WIP implementation of the WebCrypto specification for k6
GNU Affero General Public License v3.0
7 stars 4 forks source link

Adjust an extract array buffer logic #72

Open olegbespalov opened 6 months ago

olegbespalov commented 6 months ago

What?

We have to adjust how we get a copy of input data.

Currently, we do read the buffer directly: https://github.com/grafana/xk6-webcrypto/blob/2a5c460f6624b2b42a188eec09c24a95b3dcabef/webcrypto/goja.go#L24-L27

but we should do this as specifications suggest: https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy

Context

The issue was found during the work on the ECDSA where test cases use subarray's so currently, there is a workaround with copying array implemented https://github.com/grafana/xk6-webcrypto/pull/69/commits/ec27d05813b555efbeb268cad6dff6ee09dd14f9

When this adjustment is done, we should remove this workaround.

Why?

Users could modify the variables, but the buffer will contain the original values.

Here is an example of pseudo-code.

Let's say we have a JavaScript function foo mapped to Golang's implementation Foo(v goja.Value). Foo accepts only one argument, a, which is supposed to be an ArrayBuffer.

// We have some data
let data = new Uint8Array([48, 129, 135, 2, 1]);

// We'd like to create a new array that contains only the first two elements
// [48, 129]
let a = data.subarray(0, 2);

//We pass a variable to a foo, and expect that foo should process [48, 129]
foo(a)

In golang we have an implementation like:

func Foo(v goja.Value) {
   asObject := v.ToObject(rt)

   // The problem is that the buffer keeps a reference to an original buffer of data
   // and the result will be []byte{48, 129, 135, 2, 1}
   ab, ok = asObject.Get("buffer").Export().(goja.ArrayBuffer)
   if !ok {
      panic("not an array buffer")
   }

   bytes := ab.Bytes()
   bytesCopy := make([]byte, len(bytes))
   copy(bytesCopy, bytes)

   // we expect bytesCopy expecting that it will contain  [48, 129]
   // but in fact it will be original data with [48, 129, 135, 2, 1]
}