Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
adolfoportilla opened this issue Oct 2, 2019 · 2 comments

Comments

@adolfoportilla
Copy link

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
	}
}
@olliefr
Copy link

olliefr commented Nov 23, 2020

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)

@h2non
Copy link
Owner

h2non commented Nov 23, 2020

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

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

No branches or pull requests

3 participants