Skip to content

buildRoute(De)Compress doesn't handle non-compressible content if a custom onUnsupported handler is defined #305

@YTheon

Description

@YTheon

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.28.1

Plugin version

7.0.3

Node.js version

22.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10 22H2

Description

Hi!

I think I found a bug in these functions.

    let stream, encoding
    const noCompress =
      // don't compress on x-no-compression header
      (req.headers['x-no-compression'] !== undefined) ||
      // don't compress if not one of the indicated compressible types
      (shouldCompress(reply.getHeader('Content-Type') || 'application/json', params.compressibleTypes) === false) ||
      // don't compress on missing or identity `accept-encoding` header
      ((encoding = getEncodingHeader(params.encodings, req)) == null || encoding === 'identity')

    if (encoding == null && params.onUnsupportedEncoding != null) {
      const encodingHeader = req.headers['accept-encoding']
      try {
        const errorPayload = params.onUnsupportedEncoding(encodingHeader, reply.request, reply)
        return next(null, errorPayload)
      } catch (err) {
        return next(err)
      }
    }

The problem seems to be that the 'x-no-compression' header or the 'Content-Type' could resolve to true value and preempt (short-circuit) assigning a value to the encoding variable. In this case the encoding == null evaluates to true and if any custom onUnsupportedEncoding function was defined it gets called regardless whether the client and server has a common negotiable compression method.
Evaluating encoding = getEncodingHeader(params.encodings, req) before the noCompress variable should solve this in both functions.

Link to code that reproduces the bug

No response

Expected Behavior

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions