Skip to content

Commit

Permalink
add option to ignore auth
Browse files Browse the repository at this point in the history
  • Loading branch information
zhammer authored and dnaeon committed Sep 10, 2024
1 parent 1ae1a38 commit 0236971
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 9 deletions.
34 changes: 25 additions & 9 deletions pkg/cassette/cassette.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ type defaultMatcher struct {
// If set to true, the default matcher will ignore matching on the
// User-Agent HTTP header.
ignoreUserAgent bool
// If set to true, the default matcher will ignore matching on the
// Authorization HTTP header.
ignoreAuthorization bool
}

// DefaultMatcherOption is a function which configures the default matcher.
Expand All @@ -220,6 +223,16 @@ func WithIgnoreUserAgent(val bool) DefaultMatcherOption {
return opt
}

// WithIgnoreAuthorization is a [DefaultMatcherOption], which configures the default
// matcher to ignore matching on the Authorization HTTP header.
func WithIgnoreAuthorization(val bool) DefaultMatcherOption {
opt := func(m *defaultMatcher) {
m.ignoreAuthorization = val
}

return opt
}

// NewDefaultMatcher returns the default matcher.
func NewDefaultMatcher(opts ...DefaultMatcherOption) MatcherFunc {
m := &defaultMatcher{}
Expand Down Expand Up @@ -294,18 +307,21 @@ func (m *defaultMatcher) matcher(r *http.Request, i Request) bool {
return false
}

requestHeader := r.Header.Clone()
cassetteRequestHeaders := i.Headers.Clone()

if m.ignoreUserAgent {
requestHeader := r.Header.Clone()
delete(requestHeader, "User-Agent")
cassetteRequestHeaders := i.Headers.Clone()
delete(cassetteRequestHeaders, "User-Agent")
if !m.deepEqualContents(requestHeader, cassetteRequestHeaders) {
return false
}
} else {
if !m.deepEqualContents(r.Header, i.Headers) {
return false
}
}

if m.ignoreAuthorization {
delete(requestHeader, "Authorization")
delete(cassetteRequestHeaders, "Authorization")
}

if !m.deepEqualContents(requestHeader, cassetteRequestHeaders) {
return false
}

if !m.bodyMatches(r, i) {
Expand Down
18 changes: 18 additions & 0 deletions pkg/cassette/cassette_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,22 @@ func TestMatcher(t *testing.T) {
}
})
})

t.Run("IgnoreAuthorization=true", func(t *testing.T) {
matcherFn := NewDefaultMatcher(WithIgnoreAuthorization(true))

t.Run("match", func(t *testing.T) {
r, i := getMatcherRequests(t)

r.Header = http.Header{
"Authorization": {"Bearer xyz"},
}

i.Headers = http.Header{}

if b := matcherFn(r, i); !b {
t.Fatalf("request should have matched")
}
})
})
}

0 comments on commit 0236971

Please sign in to comment.