Skip to content

Fix Accept-Encoding substring matching in compress middleware#1076

Open
andrewstellman wants to merge 1 commit intogo-chi:masterfrom
andrewstellman:fix-compress-accept-encoding-matching
Open

Fix Accept-Encoding substring matching in compress middleware#1076
andrewstellman wants to merge 1 commit intogo-chi:masterfrom
andrewstellman:fix-compress-accept-encoding-matching

Conversation

@andrewstellman
Copy link
Copy Markdown

Summary

matchAcceptEncoding in the compression middleware uses strings.Contains to check whether a client accepts a given encoding. This is a substring match, which produces incorrect results in two cases:

  • gzip;q=0 matches as gzip, even though q=0 means the client explicitly refused it
  • A token like xgzip matches as gzip, even though it's a different encoding name

The root cause is on line 242 of middleware/compress.go:

// Before
if strings.Contains(v, encoding) {

Fix

Replace the substring match with proper token parsing: split the encoding name from any parameters (like ;q=0.5), trim whitespace, do an exact case-insensitive comparison, and check for q=0 which means the encoding was explicitly refused.

This is a minimal change to matchAcceptEncoding only. The rest of the compression middleware is unchanged.

Tests

Five new test cases in TestMatchAcceptEncoding exercise the function directly:

Case Input Expected Before fix
exact match gzip match match (ok)
q=0 means refused gzip;q=0 no match match (bug)
substring should not match xgzip no match match (bug)
positive q-value gzip;q=0.5 match match (ok)
whitespace gzip match match (ok)

Full test suite passes (go test ./...).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant