From b207bc8ee2d28abf59dca9bd8ad4fd4c898c80dd Mon Sep 17 00:00:00 2001 From: Dan Luhring Date: Mon, 1 Feb 2021 16:59:23 -0500 Subject: [PATCH] Ensure upload base path ends in /v1 Signed-off-by: Dan Luhring --- internal/anchore/client.go | 11 ++++++++++ internal/anchore/client_test.go | 38 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/internal/anchore/client.go b/internal/anchore/client.go index 9033d4a26..b3d168063 100644 --- a/internal/anchore/client.go +++ b/internal/anchore/client.go @@ -31,6 +31,9 @@ func NewClient(cfg Configuration) (*Client, error) { basePath := ensureURLHasScheme(cfg.BasePath) // we can rely on the built-in URL parsing for the scheme, host, // port, and path prefix, as long as a scheme is present + basePath = strings.TrimSuffix(basePath, "/") + basePath = ensureURLHasSuffix(basePath, + "/v1") // We need some mechanism to ensure Syft doesn't try to communicate with the wrong API version. return &Client{ config: cfg, @@ -70,3 +73,11 @@ func ensureURLHasScheme(url string) string { return url } + +func ensureURLHasSuffix(url, suffix string) string { + if !strings.HasSuffix(url, suffix) { + return url + suffix + } + + return url +} diff --git a/internal/anchore/client_test.go b/internal/anchore/client_test.go index cf3d71b25..3aab531a0 100644 --- a/internal/anchore/client_test.go +++ b/internal/anchore/client_test.go @@ -69,3 +69,41 @@ func TestEnsureURLHasScheme(t *testing.T) { }) } } +func TestEnsureURLHasSuffix(t *testing.T) { + cases := []struct { + url string + suffix string + expected string + }{ + { + url: "http://localhost", + suffix: "/v1", + expected: "http://localhost/v1", + }, + { + url: "http://localhost/v1", + suffix: "/v1", + expected: "http://localhost/v1", + }, + { + url: "http://localhost/v1/", + suffix: "/v1", + expected: "http://localhost/v1//v1", + }, + { + url: "http://localhost-v1", + suffix: "/v1", + expected: "http://localhost-v1/v1", + }, + } + + for _, testCase := range cases { + t.Run(testCase.url, func(t *testing.T) { + result := ensureURLHasSuffix(testCase.url, testCase.suffix) + + if testCase.expected != result { + t.Errorf("expected '%s' but got '%s'", testCase.expected, result) + } + }) + } +}