h2non / gock

HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

Home Page:https://pkg.go.dev/github.com/h2non/gock

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

adolfoportilla opened this issue · 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
	}
}

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)

commented

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