Skip to content
Myr

fix: AWS Lambda: Avoid text-encoding binary data (#1235)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

So far, the AWS Lambda adapter has used `atob` to convert a Base64-encoded request body to a binary. However, `atob` returns a string, and passing that to the `Request` constructor (at least on Node.js, which Lambda runs on) results in the binary string being encoded as UTF-8. This means that if the request body contains bytes which are not in the ASCII range, they are replaced with UTF-8 multi-byte encodings, which leads to `c.req.blob()`, `c.req.formData()`, etc. returning the wrong binary data! This commit fixes the issue by replacing `atob(body)` with `Buffer.from(body, 'base64')`, which does not have that problem. The `Buffer` can be directly passed as body for `new Request()` because it implements the `Uint8Array` interface. While this makes the AWS Lambda adapter depend directly on the "node:buffer" module, this should be fine because AWS Lambda functions always run on Node.

authored by Denis Washington · committed by GitHub · parent 5090c3c · Browse files · 2 files+28 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+28 added−1 removed

  • tests:+26 added−0 removed
  • other:+2 added−1 removed

2 files+28 added−1 removed

modified:runtime_tests/lambda/index.test.ts+26 added
18 unmodified lines
19 const body = (await c.req.parseBody()) as { message: string }20 return c.text(body.message)21 })2223 app.post('/post/binary', async (c) => {24 const body = await c.req.blob()25 return c.text(`${body.size} bytes`)26 })2728 const username = 'hono-user-a'29 const password = 'hono-password-a'30 app.use('/auth/*', basicAuth({ username, password }))31 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))
120 unmodified lines
152 expect(response.statusCode).toBe(200)153 expect(response.body).toBe('Good Morning Lambda!')154 })155156 it('Should handle a POST request with binary and return a 200 response', async () => {157 const array = new Uint8Array([0xc0, 0xff, 0xee])158 const buffer = Buffer.from(array)159 const event = {160 httpMethod: 'POST',161 headers: {162 'Content-Type': 'application/x-www-form-urlencoded',163 },164 path: '/post/binary',165 body: buffer.toString('base64'),166 isBase64Encoded: true,167 requestContext: {168 domainName: 'example.com',169 },170 }171172 const response = await handler(event)173 expect(response.statusCode).toBe(200)174 expect(response.body).toBe('3 bytes')175 })176177 it('Should handle a request and return a 401 response with Basic auth', async () => {178 const event = {179 httpMethod: 'GET',180 headers: {
35 unmodified lines
modified:src/adapter/aws-lambda/handler.ts+2 added-1 removed