Skip to content
Myr

fix(etag): support multi-value If-None-Match (#1199)

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

* chore(etag): reduce global state in tests Previously, the `etag` tests used a single Hono `app` that was instantiated statically before the tests. Having a shared app increases the chances of inter-test conflicts and makes it impossible to modify the app for a single test. This, in turn, makes it harder for test maintainers to see the connection between the app configuration and the expectations. This commit moves the creation of the `app` into a `beforeEach` block and moves any app configuration that relates to a single test case into that test case. * perf(etag): don't override ETags from upstream Previously, the `etag` middleware would always compute an `ETag` header based on the SHA-1 of the `Response` body. In cases where the upstream response already includes the header, this wastefully clones the response, reads the body into memory, and computes a hash. This commit changes the middleware to bypass the hash computation if the `Response` already has an ETag. * perf(etag): 304s include only necessary headers The spec[^1] for 304 Not Modified says, > The server generating a 304 response MUST generate any of the > following header fields that would have been sent in a 200 (OK) > response to the same request: > > * Content-Location, Date, ETag, and Vary > * Cache-Control and Expires (see [CACHING]) > > Since the goal of a 304 response is to minimize information transfer > when the recipient already has one or more cached representations, a > sender SHOULD NOT generate representation metadata other than the > above listed fields unless said metadata exists for the purpose of > guiding cache updates (e.g., Last-Modified might be useful if the > response does not have an ETag field). Previously, the `etag` middleware was sending all headers from the original response except for `content-type` (omitted by `Context.prototype.set res`) and `content-length` (omitted by the `etag` middleware itself). This commit changes the middleware to include only the headers required with the spec, upgrading it from _conditionally compliant_ to _fully compliant_. The list is configurable as `options.retainedHeaders`. [^1]: https://www.rfc-editor.org/rfc/rfc9110#name-304-not-modified * fix(etag): Support multi-value If-None-Match The spec[^1] for `If-None-Match` says, > If the field value is a list of entity tags, the condition is false if > one of the listed tags matches the entity tag of the selected > representation. and provides these examples: ``` If-None-Match: "xyzzy" If-None-Match: W/"xyzzy" If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz" If-None-Match: W/"xyzzy", W/"r2d2xxxx", W/"c3piozzzz" If-None-Match: * ``` The value `*` isn't relevant for this middleware, but the other values are. This commit adds support for multi-value comma-separated ETags in the `If-None-Match` header. [^1]: https://www.rfc-editor.org/rfc/rfc9110#name-if-none-match * perf(etag): prefer Header.prototype.get Previously, the `etag` middleware used `c.req.header(...)` to access the `If-None-Match` header. This method works, but is less efficient than accessing the value via the raw `Headers` object. Additionally, the middleware was trying multiple case versions for the same header, but header-lookup is case-insensitive, so it was wasting time on requests that lacked the header altogether. This change also makes `etag` consistent with the other middleware in this repo (e.g. `basic-auth`, `compress`), which all use `c.req.headers.get(...)` to access headers.

authored by James A Rosen · committed by GitHub · parent 5965102 · Browse files · 3 files+155 added−61 removed
This commit

State

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

Diff stats

3 files+155 added−61 removed

  • tests:+83 added−41 removed
  • other:+72 added−20 removed

3 files+155 added−61 removed

modified:deno_dist/middleware/etag/index.ts+36 added-10 removed
modified:src/middleware/etag/index.test.ts+83 added-41 removed
modified:src/middleware/etag/index.ts+36 added-10 removed
1import type { MiddlewareHandler } from '../../types'2import { sha1 } from '../../utils/crypto'34type ETagOptions = {5 retainedHeaders?: string[],5 weak: boolean6 weak?: boolean7}89/**10 * Default headers to pass through on 304 responses. From the spec:11 * > The response must not contain a body and must include the headers that12 * > would have been sent in an equivalent 200 OK response: Cache-Control,13 * > Content-Location, Date, ETag, Expires, and Vary.14 */15const RETAINED_304_HEADERS = [16 'cache-control', 'content-location', 'date', 'etag', 'expires', 'vary'17]1819function etagMatches(etag: string, ifNoneMatch: string | null) {20 return ifNoneMatch != null && ifNoneMatch.split(/,\s*/).indexOf(etag) > -121}228export const etag = (options: ETagOptions = { weak: false }): MiddlewareHandler => {23export const etag = (options?: ETagOptions): MiddlewareHandler => {24 const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS25 const weak = options?.weak ?? false2627 return async (c, next) => {10 const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')28 const ifNoneMatch = c.req.headers.get('If-None-Match')2930 await next()3132 const res = c.res as Response15 const clone = res.clone()16 const hash = await sha1(res.body || '')33 let undisturbedRes = res34 let etag = res.headers.get('ETag')3536 if (!etag) {37 undisturbedRes = res.clone()38 const hash = await sha1(res.body || '')18 const etag = options.weak ? `W/"${hash}"` : `"${hash}"`39 etag = weak ? `W/"${hash}"` : `"${hash}"`40 }4120 if (ifNoneMatch && ifNoneMatch === etag) {21 await clone.blob() // Force using body42 if (etagMatches(etag, ifNoneMatch)) {43 await undisturbedRes.blob() // Force using body44 c.res = new Response(null, {45 status: 304,46 statusText: 'Not Modified',47 headers: {48 ETag: etag,49 },50 })29 c.res.headers.delete('Content-Length')51 c.res.headers.forEach((_, key) => {52 if (retainedHeaders.indexOf(key.toLowerCase()) === -1) {53 c.res.headers.delete(key)54 }55 })56 } else {31 c.res = new Response(clone.body, clone)57 c.res = new Response(undisturbedRes.body, undisturbedRes)58 c.res.headers.set('ETag', etag)59 }60 }61}