chi icon indicating copy to clipboard operation
chi copied to clipboard

Compress middleware: matchAcceptEncoding uses substring match and ignores q=0

Open queelius opened this issue 8 months ago • 1 comments

Description

The matchAcceptEncoding function in middleware/compress.go uses strings.Contains to match encoding names in the Accept-Encoding header. This has two problems:

1. Substring matching produces false positives

func matchAcceptEncoding(accepted []string, encoding string) bool {
	for _, v := range accepted {
		if strings.Contains(v, encoding) {   // substring match, not exact
			return true
		}
	}
	return false
}

For example:

  • Accept-Encoding: br incorrectly matches encoding b (since "br" contains "b")
  • Accept-Encoding: bgzip incorrectly matches encoding gzip

2. Quality value q=0 is ignored

Per RFC 9110 Section 12.5.3, a quality value of q=0 means the encoding is not acceptable. But strings.Contains("gzip;q=0", "gzip") returns true, so the middleware will compress with gzip even when the client explicitly rejects it.

Reproduction

// These all incorrectly return true:
matchAcceptEncoding([]string{"gzip;q=0"}, "gzip")   // should be false (q=0 = not acceptable)
matchAcceptEncoding([]string{"br"}, "b")             // should be false (not exact match)
matchAcceptEncoding([]string{"bgzip"}, "gzip")       // should be false (not exact match)

Fix

Parse the encoding name properly by splitting on ; to separate quality parameters, trimming whitespace, performing exact string comparison, and rejecting q=0.

queelius avatar Mar 25 '26 08:03 queelius

Took a look — confirmed both issues:

  1. strings.Contains(v, encoding) produces false positives like br matching b and bgzip matching gzip
  2. q=0 is silently ignored — gzip;q=0 matches gzip and the middleware compresses anyway

Plan: rewrite matchAcceptEncoding to split each header element on ;, trim whitespace, exact-compare the encoding token, and parse the q parameter (rejecting q=0). Will add table tests covering the substring false-positives, the q=0 case, the standard q=1.0 / q=0.5 cases, and case-insensitivity per RFC 9110. I can send a PR if that sounds right.

barry3406 avatar Apr 10 '26 10:04 barry3406