gock icon indicating copy to clipboard operation
gock copied to clipboard

MatchHeader does match if value has special characters (., /, ;, etc)

Open adolfoportilla opened this issue 6 years ago • 2 comments

gock.MatchHeader accepts two strings (key, value), but the underlying function that matches the mock request Headers against the real request headers is regexp.MatchString. (File: matchers.go)

The issue is that regexp.MatchString takes a regex pattern expression and a string.

That causes the problem of matching headers that have parentheses or other special characters.

Example:

// main.go

req, err := http.NewRequest("GET", "http://example.com", nil)
req.Header.Add("User-Agent", "Agent (version1.0)")

// main_test.go

gock.New("http://example.com").
  MatchHeader("User-Agent", "Agent (version1.0)").  // Will never match the request
  Get("/").
  Reply(200).
  BodyString("Success")

A way of fixing the issue is that the key and value are escaped first using regexp.QuoteMeta(key) & regexp.QuoteMeta(value), before being passed to the regexp.MatchString function.

matchers.go

for _, field := range req.Header[key] {
        escapedValue := regexp.QuoteMeta(value[0])  // Something like this
        escapedField := regexp.QuoteMeta(field)
	match, err = regexp.MatchString(escapedValue, escapedField)
	if err != nil {
		return false, err
	}
	if match {
		break
	}
}

adolfoportilla avatar Oct 02 '19 17:10 adolfoportilla

I've just hit this bug in 1.0.15 which led me here. Are there any plans to release this to production, please? As in 1.0.16 or whatever)

olliefr avatar Nov 23 '20 19:11 olliefr

A new version tag is now available: v1.0.16.

h2non avatar Nov 23 '20 20:11 h2non