From dc939a06a937d50ef65de81d67b3f3a07e409cce Mon Sep 17 00:00:00 2001 From: Joseph Crosland Date: Wed, 8 Jun 2022 10:13:00 -0700 Subject: [PATCH] crda: clone url when creating a new matcher (#633) It is currently possible to modify the url after it's assigned to the matcher struct i.e. when newMatcher is called subsequently. This change ensures any url passed to the constructor (via the option method) is cloned. Signed-off-by: crozzy --- crda/remotematcher.go | 8 ++++++-- crda/remotematcher_test.go | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crda/remotematcher.go b/crda/remotematcher.go index d9114f580..d63ac9f58 100644 --- a/crda/remotematcher.go +++ b/crda/remotematcher.go @@ -118,9 +118,13 @@ func withClient(c *http.Client) option { } // WithURL sets the URL that the matcher should use for requests. -func withURL(url *url.URL) option { +func withURL(u *url.URL) option { return func(m *matcher) error { - m.url = url + if u == nil { + return nil + } + urlClone := *u + m.url = &urlClone return nil } } diff --git a/crda/remotematcher_test.go b/crda/remotematcher_test.go index 91198b521..aca50560e 100644 --- a/crda/remotematcher_test.go +++ b/crda/remotematcher_test.go @@ -58,6 +58,25 @@ func mkMatcher(t *testing.T, srv *httptest.Server) *matcher { return m } +func TestMatcherURL(t *testing.T) { + expectedURL := "https://gw.api.openshift.io/api/v2/vulnerability-analysis?user_key=algo" + url, err := url.Parse("https://gw.api.openshift.io/api/v2/") + if err != nil { + t.Fatal(err) + } + _, err = newMatcher("pypi", "algo", withURL(url)) + if err != nil { + t.Fatal(err) + } + m2, err := newMatcher("maven", "algo", withURL(url)) + if err != nil { + t.Fatal(err) + } + if m2.url.String() != expectedURL { + t.Fatalf("Invalid url %s, expected %s", m2.url.String(), expectedURL) + } +} + func TestRemoteMatcher(t *testing.T) { t.Parallel() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {