Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Read all chunks when hashing a readable stream #2911

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions runtime_tests/bun/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Hono } from '../../src/index'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { jsx } from '../../src/jsx'
import { basicAuth } from '../../src/middleware/basic-auth'
import { etag } from '../../src/middleware/etag'
import { jwt } from '../../src/middleware/jwt'
import { HonoRequest } from '../../src/request'

Expand Down Expand Up @@ -316,3 +317,21 @@ async function deleteDirectory(dirPath) {
await fs.unlink(dirPath)
}
}

describe('Etag Middleware', () => {
it('Should not be the same etag - Uint8Array', async () => {
const app = new Hono()
app.use('/etag/*', etag())
app.get('/etag/ui1', (c) => {
return c.body(new Uint8Array(20000))
})
app.get('/etag/ui2', (c) => {
return c.body(new Uint8Array(22000))
})

let res = await app.request('http://localhost/etag/ui1')
const hash = res.headers.get('Etag')
res = await app.request('http://localhost/etag/ui2')
expect(res.headers.get('ETag')).not.toBe(hash)
})
})
16 changes: 12 additions & 4 deletions src/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,19 @@
if (data instanceof ReadableStream) {
let body = ''
const reader = data.getReader()
await reader?.read().then(async (chuck) => {
const value = await createHash(chuck.value || '', algorithm)
let chunks = 0
let chunk = await reader?.read()
while (chunk && !chunk.done) {
chunks++
const value = await createHash(chunk.value || '', algorithm)
body += value
})
return body

chunk = await reader?.read()
}
if (chunks === 1) {
return body
}
data = body

Check warning on line 49 in src/utils/crypto.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/crypto.ts#L49

Added line #L49 was not covered by tests
}
if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) {
sourceBuffer = data
Expand Down