Skip to content

Commit

Permalink
Merge pull request #39 from diversario/fix-prom-client-auth
Browse files Browse the repository at this point in the history
Use Prometheus bearer token only when provided
  • Loading branch information
vishnuchalla authored Nov 30, 2023
2 parents d38a199 + ea011fc commit 1b0a1cc
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
6 changes: 5 additions & 1 deletion prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ func (bat authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if bat.username != "" {
req.SetBasicAuth(bat.username, bat.password)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bat.token))

if bat.token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bat.token))
}

return bat.Transport.RoundTrip(req)
}

Expand Down
51 changes: 51 additions & 0 deletions prometheus/prometheus_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package prometheus

import (
"encoding/base64"
"fmt"
"net/http"
"time"
Expand Down Expand Up @@ -33,6 +34,56 @@ var _ = Describe("Tests for Prometheus", func() {
Expect(count).To(BeEquivalentTo(0))
Expect(err).To(BeNil())
})

It("Test2 bearer header is used when token is provided", func() {
url := "https://example.com/api"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
_, err = bat.RoundTrip(req)
Expect(req.Header.Get("Authorization")).To(Equal("Bearer someRandomToken"))
//Asserting no of times mocks are called
Expect(count).To(BeEquivalentTo(0))
Expect(err).To(BeNil())
})

It("Test3 basic auth header is used when no token is provided", func() {
bat.token = ""
url := "https://example.com/api"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
_, err = bat.RoundTrip(req)

encodedAuthHeader := base64.StdEncoding.EncodeToString([]byte("someRandomUsername:someRandomPassword"))

Expect(req.Header.Get("Authorization")).To(Equal("Basic " + encodedAuthHeader))
//Asserting no of times mocks are called
Expect(count).To(BeEquivalentTo(0))
Expect(err).To(BeNil())
})

It("Test4 no auth header set when auth details are omitted", func() {
bat.token = ""
bat.username = ""
bat.password = ""
url := "https://example.com/api"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
fmt.Println("Failed to create request:", err)
return
}
_, err = bat.RoundTrip(req)

Expect(req.Header.Get("Authorization")).To(Equal(""))
//Asserting no of times mocks are called
Expect(count).To(BeEquivalentTo(0))
Expect(err).To(BeNil())
})
})

Context("Tests for NewClient()", func() {
Expand Down

0 comments on commit 1b0a1cc

Please sign in to comment.